链接:
https://leetcode.com/problems/combinations/
大意:
给定一个整数n和一个整数k,在[1,n]中取出k个数作为组合,返回所有的组合。例子:
思路:
回溯法。优化使用剪枝
代码:
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new ArrayList<>();
if (k <= 0 || k > n)
return res;
dfs(n, 1, k, res, new LinkedList<>());
return res;
}
// v为当前值
public void dfs(int n, int v, int k, List<List<Integer>> res, LinkedList<Integer> list) {
// 剪枝 当当前值i到末尾值n区间内的数+当前list已有的数目少于k时,直接跳出循环,表示不可达
for (int i = v; n - i + 1 + list.size() >= k; i++) {
list.addLast(i);
if (list.size() == k) {
res.add(new ArrayList<>(list));
} else {
dfs(n, i + 1, k, res, list);
}
list.removeLast();
}
}
}
结果:
结论:
回溯+剪枝