Combinations
题目地址:
https://leetcode.com/problems/combinations/#/description
题目:
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
For example,
If n = 4 and k = 2, a solution is:
If n = 4 and k = 2, a solution is:
[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
解题思路:
这道题就是dfs,然后控制一下list的size的大小。
代码:
public class Combinations { public List<List<Integer>> combine(int[] nums, int k) { List<List<Integer>> rst = new ArrayList<List<Integer>>(); if(nums == null || nums.length == 0 || k == 0 || nums.length < k){ return rst; } List<Integer> list = new ArrayList<Integer>(); helper(nums, rst, list, k, 0); return rst; } private void helper(int[] nums, List<List<Integer>> rst, List<Integer> list, int k, int pos) { if(list.size() == k){ rst.add(new ArrayList<>(list)); return; } for(int i = pos; i <= nums.length - 1; i++){ list.add(nums[i]); helper(nums, rst, list, k, i + 1); list.remove(list.size() - 1); } } public static void main(String[] args){ int[] nums = {1, 2, 3, 4}; Combinations combinations = new Combinations(); List<List<Integer>> rst = combinations.combine(nums, 2); System.out.println(rst); } }

Comments
Post a Comment