解题思路:
回溯
提交代码:
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
List<Integer> curComb = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
curComb.add(i+1);
makeCombination(curComb, n, k, ans);
curComb.remove(curComb.size()-1);
}
return ans;
}
public void makeCombination(List<Integer> curComb, int n, int k, List<List<Integer>> ans) {
if (curComb.size() == k) {
List<Integer> tmp=new ArrayList<Integer>();
tmp.addAll(curComb);
ans.add(tmp);
return;
}
for (int i = curComb.get(curComb.size()-1); i < n; i++) {
curComb.add(i+1);
makeCombination(curComb, n, k, ans);
curComb.remove(curComb.size()-1);
}
}
}
运行结果:

本文介绍了一种使用回溯算法解决组合问题的方法。通过递归地构建可能的组合,算法有效地生成了所有可能的k个元素组合,从n个不同的元素中选择。代码示例展示了如何实现这一算法,并提供了运行结果。
369

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



