Combinations (M)
Given two integers n and k, return all possible combinations of k numbers out of 1 … n.
Example:
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
题意
从n个数中选取k个组成集合,输出所有这样的集合。
思路
回溯法,注意剪枝。
代码实现
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> ans = new ArrayList<>();
combine(n, k, 1, new ArrayList<>(), ans);
return ans;
}
private void combine(int n, int k, int cur, List<Integer> list, List<List<Integer>> ans) {
if (list.size() == k) {
ans.add(new ArrayList<>(list));
return;
}
// 只有当剩余元素数加上已加入列表元素数大于等于k时,才需要继续递归
for (int i = cur; n - i + 1 >= k - list.size(); i++) {
list.add(i);
combine(n, k, i + 1, list, ans);
list.remove(list.size() - 1);
}
}
}
本文探讨了从n个数中选择k个数的所有可能组合。通过使用回溯法,有效地解决了组合问题,并提供了详细的代码实现。文章重点介绍了算法的思路和剪枝技巧。
463

被折叠的 条评论
为什么被折叠?



