题目描述:
给定两个整数 n 和 k,返回 1 … n 中所有可能的 k 个数的组合。
输入:
n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
题意:
题目描述
题解:
基础dfs
代码:
class Solution {
List<List<Integer>> ans = new ArrayList<>();
public List<List<Integer>> combine(int n, int k) {
for(int i = 1; i <= n; i ++){
List<Integer> list = new ArrayList<>();
list.add(i);
combine_dfs(i + 1,n,k - 1,list);
list.remove(list.size() - 1);
}
return ans;
}
public void combine_dfs(int st,int n,int k,List<Integer> list){
if(k == 0){
ans.add(new ArrayList<>(list));
return ;
}
for(int i = st; i <= n; i ++){
list.add(i);
combine_dfs(i + 1,n,k - 1,list);
list.remove(list.size() - 1);
}
}
}