组给出两个整数n和k,返回从1......n中选出的k个数的组合。
样例
例如 n = 4 且 k = 2
返回的解为:
[[2,4],[3,4],[2,3],[1,2],[1,3],[1,4]]
注意事项
不需要在意组合的顺序,但是你应该确保组合中的数字是有序的
解题思路:
标准DFS解法
public class Solution {
/**
* @param n: Given the range of numbers
* @param k: Given the numbers of combinations
* @return: All the combinations of k numbers out of 1..n
*/
public List<List<Integer>> combine(int n, int k) {
// write your code here
List<List<Integer>> res = new ArrayList<>();
dfs(n, k, new ArrayList<Integer>(), res, 1);
return res;
}
private void dfs(int n, int k, List<Integer> list, List<List<Integer>> res, int index){
if(list.size() == k){
res.add(new ArrayList<Integer>(list));
return;
}
for(int i = index; i <= n; i++){
list.add(i);
dfs(n, k, list, res, i + 1);
list.remove(list.size() - 1);
}
}
}
//剪枝优化:
//到现在还有k - list.size()个空位,也就是[i...n]至少要有k-list.size()个空位
//所以i最多为n - (k - list.size()) + 1
将dfs中的for循环改为:
for(int i = index; i <= n - (k - list.size()) + 1; i++)