组合

问题陈述

给定两个整数 nk,返回 1 … n 中所有可能的 k 个数的组合。

1
2
3
4
5
6
7
8
9
10
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]

思路实现

同样可以用一个决策树进行回溯求解。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> combinations=new ArrayList<>();
List<Integer> res=new ArrayList<>();
backtrack(combinations,res,n,k,1);//n的遍历范围为1~n
return combinations;
}

private void backtrack(List<List<Integer>> combinations,List<Integer> res,int n,int k,int start){
if(k==0){
combinations.add(new ArrayList<>(res));
return;
}
for(int i=start;i<=n-k+1;i++){//对于n个数,选择了一位,剩下n-1位。
res.add(i);
backtrack(combinations,res,n,k-1,i+1);//k--,i++
res.remove(res.size()-1);
}
}
}