给定两个整数 n 和 k,返回 1 … n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combinations
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public List<List<Integer>> combine(int n, int k) {
boolean [] vis = new boolean [n+1];
List<List<Integer>> res = new LinkedList<>();
List<Integer> path = new LinkedList<>();
int deep =0 ;
int first=1;
backtrack(res,path,deep,n,k,vis,first);
return res;
}
public void backtrack(List<List<Integer>> res,List<Integer> path, int deep ,int n,int k ,boolean [] vis ,int first){
if(k==deep){
res.add( new LinkedList(path));
return;
}
for(int i=first;i<=n;i++){
// System.out.println("i is "+ deep);
if(!vis[i]){
vis[i]=true;
path.add(i);
deep++;
backtrack(res,path,deep,n,k,vis,i+1);
deep--;
vis[i]=false;
path.remove(path.size() - 1);
}
}
}
}
本文详细解析了LeetCode上的一道经典题目——组合问题。给定两个整数n和k,文章介绍了如何寻找并返回1到n中所有可能的k个数的组合。通过深入分析递归回溯算法,展示了如何利用路径列表和访问标记来实现解决方案。

980

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



