Special backtracking Leetcode of -77. Composition (Combinations)

Special backtracking Leetcode of -77. Composition (Combinations)


 

Given two integers  n  and  k , ... return. 1  possible all  k  combination number.

Example:

Input: n = 4, k = 2 
Output: 
[ 
  [2,4], 
  [3,4], 
  [2,3], 
  [1,2], 
  [1,3], 
  [1,4], 
]




Analysis: This question is very simple, get back or not taken on the line.

AC Code:
class Solution {
    List<List<Integer>> ans = new ArrayList<>();
    public List<List<Integer>> combine(int n, int k) {
        if (n <= 0 || k <= 0 || n < k) {
            return ans;
        }
        
        dfs(n,k,1,new Stack<Integer>());
        
        return ans;
    }
    
    
    public void dfs(int n,int k,int now,Stack<Integer> s){
        if(s.size()==k){
            ans.add(new ArrayList<Integer>(s));
            return;
        }

        for(int i= now;i<=n;i++){
            s.add(i);
            dfs(n,k,(i+1),s);
            s.pop();
        }
        
    }
    
}

 



 

Guess you like

Origin www.cnblogs.com/qinyuguan/p/11330154.html