题目链接
题目描述
给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 k 个数的组合。
你可以按 任何顺序 返回答案。
示例 1:
输入:n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
示例 2:
输入:n = 1, k = 1
输出:[[1]]
提示:
1 <= n <= 20
1 <= k <= n
求解思路
- 回溯法:在
dfs()
方法中,从后向前进行搜索,i
表示搜索的n
个数字还剩下i
个,d
表示还需要再选d
个数字,如果选满了则将temp
添加入ans
结果中并返回。 - 接下来开始判断:如果剩下的数字比还需要选的数字要多,则可以先不选择当前数字;否则就必须选上。递归完成之后进行回溯。
实现代码
class Solution {
int k;
List<Integer> temp = new ArrayList<>();
List<List<Integer>> ans = new ArrayList<>();
public List<List<Integer>> combine(int n, int k) {
this.k = k;
dfs(n);
return ans;
}
public void dfs(int i) {
int d = k - temp.size(); //还需要选d个数字
if (d == 0) {
ans.add(new ArrayList<>(temp));
return;
}
if (i > d) { //不选i
dfs(i - 1);
}
temp.add(i); //选上i
dfs(i - 1);
temp.remove(temp.size() - 1);
}
}