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:
[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
思路: 回溯法 剪枝叶
public class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if(n == 0 || k == 0 || n < k) {
return result;
}
List<Integer> list = new ArrayList<Integer>();
helper(result, list, 1, n, k);
return result;
}
public void helper(List<List<Integer>> result, List<Integer> list, int i, int n , int k) {
if(list.size() == k) {
result.add(new ArrayList<Integer>(list));
return;
}
for(int j = i; j <= n; j++) {
list.add(j);
helper(result, list,j + 1, n, k);
list.remove(list.size() - 1);
}
}
}