使用backtrack的方法。对过程进行递归。
public class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> combs = new ArrayList<List<Integer>>();
combine(combs, new ArrayList<Integer>(), 1, n, k);
return combs;
}
private void combine(List<List<Integer>> combs, List<Integer> comb, int start, int n, int k) {
if (k == 0) {
combs.add(new ArrayList<Integer>(comb));
return;
}
for (int i = start; i <= n; i++) {
comb.add(i);
combine(combs, comb, i + 1, n, k - 1);
// before enter next step, delete old step
comb.remove(comb.size() - 1);
}
}
}
本文介绍了一种使用回溯法生成所有可能的k个数组合的算法实现。通过递归方式,从1到n中选择k个不同的整数,并将这些组合以列表的形式返回。文章详细展示了如何利用递归和回溯思想解决这一问题。
649

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



