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<List<Integer>> combine(int n, int k) {
        result = new ArrayList<>();
        List<Integer> ans = new ArrayList<Integer>();
        dfs(ans,n,k,1);
        return result;
    }
    
    void dfs(List<Integer> ans, int n, int k, int depth){
        if(ans.size()==k) {
            List<Integer> new_ans = new ArrayList<Integer>(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<List<Integer>> result;
}
原文地址:https://www.cnblogs.com/qionglouyuyu/p/10929529.html