https://leetcode-cn.com/problems/combinations/php
给定两个整数 n
和 k
,返回 1 ... n
中全部可能的 k
个数的组合。ide
示例:优化
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
输入: n = 4, k = 2输出:[[2,4],[3,4],[2,3],[1,2],[1,3],[1,4],]
标签:回溯与剪枝spa
n表示范围为1...n,balance表示剩余空间,start表示开始位置,list为回溯列表3d
判断balance == 0,若是为0则表明list中已经存入k个数,拷贝list存入结果ans中code
若是不为0,从start位置开始递归调用,现将当前位置数据加入list中,并进入下一层,等待返回后将本层加入的数据移除,本质就是树的构造过程orm
其中循环结束条件默认为最大值到n,这里能够优化进行剪枝,好比n=4,k=3
时,若是列表从start=3
也就是[3]
开始,那么该组合必定不存在,由于至少要k=3
个数据,因此剪枝临界点为n-balance+1
blog
class Solution {
private List<List<Integer>> ans = new ArrayList<>();
public List<List<Integer>> combine(int n, int k) {
getCombine(n, k, 1, new ArrayList<>());
return ans;
}
public void getCombine(int n, int k, int start, List<Integer> list) {
if(k == 0) {
ans.add(new ArrayList<>(list));
return;
}
for(int i = start;i <= n - k + 1;i++) {
list.add(i);
getCombine(n, k - 1, i+1, list);
list.remove(list.size() - 1);
}
}
}
class Solution {private List<List<Integer>> ans = new ArrayList<>();public List<List<Integer>> combine(int n, int k) {getCombine(n, k, 1, new ArrayList<>());return ans;}public void getCombine(int n, int k, int start, List<Integer> list) {if(k == 0) {ans.add(new ArrayList<>(list));return;}for(int i = start;i <= n - k + 1;i++) {list.add(i);getCombine(n, k - 1, i+1, list);list.remove(list.size() - 1);}}}