77. Combinations (JAVA)

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],
]

 

带回溯的递归。(带回溯没法用循环实现)

class Solution {
    public List> combine(int n, int k) {
        result = new ArrayList<>();
        List ans = new ArrayList();
        dfs(ans,n,k,1);
        return result;
    }
    
    void dfs(List ans, int n, int k, int depth){
        if(ans.size()==k) {
            List new_ans = new ArrayList(ans);
            result.add(new_ans);
            return;
        }
        if(depth>n){
            return;
        }
        
        ans.add(depth);
        dfs(ans,n,k,depth+1);
        ans.remove(ans.size()-1);
        dfs(ans,n,k,depth+1);
        
    }
    
    private List> result;
}

 

转载于:https://www.cnblogs.com/qionglouyuyu/p/10929529.html

你可能感兴趣的:(77. Combinations (JAVA))