leetcode77 (combination: backtracking method)

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

This question is actually the same as Leetcode17 (seeking the character combination of the phone number). In fact, it can also be said that the universality of the backtracking method is very strong in the question involving enumeration + combination.

Solution: Maintain a stack and save the combination. Using the backtracking method (recursion), exhaust all combinations, when the number of elements in the stack is k, insert the results in the stack into the result set.

class Solution {
    
    
    private final List<List<Integer>>res=new ArrayList<>();
    public List<List<Integer>> combine(int n, int k) {
    
    
        DFS(new boolean[n],new Stack<>(),n,k,1);
        return res;
    }
    private void DFS(boolean[]search,Stack<Integer>subRes,int n,int k,int min){
    
    
        if(subRes.size()+n-min+1<k)
            return;
        if(subRes.size()==k) {
    
    
            res.add(new ArrayList<>(subRes));
            return;
        }
        for(int i=min;i<=n;i++){
    
    
            if(!search[i-1]) {
    
    
                subRes.add(i);
                search[i-1]=true;
                DFS(search,subRes,n,k,i+1);
                search[i-1]=false;
                subRes.pop();
            }
        }
    }
}

Guess you like

Origin blog.csdn.net/CY2333333/article/details/108479179