给定两个整数 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);
}
}
}
}