77.组合
题目描述
给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 k 个数的组合。
你可以按 任何顺序 返回答案。
示例1:
输入:n=4,k=2n = 4, k = 2n=4,k=2
输出:[[2,4],[3,4],[2,3],[1,2],[1,3],[1,4],][
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
][[2,4],[3,4],[2,3],[1,2],[1,3],[1,4],]
示例2:
输入:n=1,k=1n = 1, k = 1n=1,k=1
输出:[[1]][[1]][[1]]
思路
看到题目就知道是回溯的题了,题目中要求输出的是组合,也就是说,无顺序不重复的固定长度的集合输出。
题解
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combine(int n, int k) {
helper(n,k,1);
return result;
}
public void helper(int n,int k,int startIndex){
if(path.size() == k){
result.add(new ArrayList<>(path));
return;
}
for(int i = startIndex;i<= n-(k-path.size())+1;i++){
path.add(i);
helper(n,k,i+1);
path.removeLast();
}
}
}
总结
回溯此类有很多看起来相似但并不相同的题目,但好在回溯类的题确实是有一些套路的,还是要多看多练。
1103

被折叠的 条评论
为什么被折叠?



