Combinations ——LeetCode

时间:2023-03-09 04:43:15
Combinations ——LeetCode

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

For example,
If n = 4 and k = 2, a solution is:

[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]

题目大意:给两个数n和k,输出所有长度为k的排列组合。

解题思路:当做求子集来做,大于k的剪枝剪掉,最后再筛一下结果集。

    public List<List<Integer>> combine(int n, int k) {

        List<List<Integer>> res = new ArrayList<>();
if(n==0){
return res;
}
res.add(new ArrayList<Integer>());
helper(res,k,n);
Iterator<List<Integer>> itr = res.iterator();
while(itr.hasNext()){
if(itr.next().size()!=k){
itr.remove();
}
}
return res;
} private void helper(List<List<Integer>> res,int k,int n){ for(int j=1;j<=n;j++){
int currSize = res.size();
for(int i=0;i<currSize;i++){
List<Integer> x = new ArrayList<>(res.get(i));
x.add(j);
if(x.size()>k)
continue;
res.add(new ArrayList<>(x));
}
}
}