Java LeetCode 77. Combination

Given two integers n and k, return all possible combinations of k numbers in 1...n.
Example:
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]

class Solution {
    
    
    public List<List<Integer>> combine(int n, int k) {
    
    
        Deque<Integer> que = new LinkedList();
        List<List<Integer>> res = new ArrayList();
        back(que,1,n,k,res);
        return res;
    }
    public void back(Deque<Integer> que,int start,int n,int k,List<List<Integer>> res){
    
    
        if(que.size()==k){
    
    
            res.add(new ArrayList(que));
        }

        for(int i=start;i<=n;i++){
    
    

            que.offerLast(i);

            back(que,i+1,n,k,res);

            que.pollLast();
        }

    }
}

Guess you like

Origin blog.csdn.net/sakura_wmh/article/details/110847656