LeetCode 77 组合
LeetCode77 组合
题目描述
给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
样例
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
算法分析
- 枚举位置、加上顺序条件,保证唯一
时间复杂度
Java代码
class Solution {
static List<List<Integer>> ans = new ArrayList<List<Integer>>();
static List<Integer> t = new ArrayList<Integer>();
static void dfs(int n, int k, int u, int start){
if(u == k){
ans.add(new ArrayList<Integer>(t));
return;
}
for(int i = start; i <= n; i ++){
t.add(i);
dfs(n,k,u+1,i+1);
t.remove(t.size()-1);
}
}
public List<List<Integer>> combine(int n, int k) {
ans.clear();
dfs(n,k,0,1);
return ans;
}
}

浙公网安备 33010602011771号