Leetcode之回溯法专题-77. 组合(Combinations)

Leetcode之回溯法专题-77. 组合(Combinations)


 

给定两个整数 n 和 k,返回 1 ... 中所有可能的 k 个数的组合。

示例:

输入: n = 4, k = 2
输出:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]




分析:这题很简单,回溯取还是不取就行了。

AC代码:
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();
        }
        
    }
    
}


猜你喜欢

转载自www.cnblogs.com/qinyuguan/p/11330154.html
今日推荐