LeetCode 77. Combinations (组合)

题目标签:Backtracking

  利用dfs,建立一个 tempList 递归加入 1.2.3.4....直到 size = k 就存入 res 返回;

  具体看code。

 

Java Solution: 

Runtime:  28 ms, faster than 22.99% 

Memory Usage: 42.6 MB, less than 6.52%

完成日期:12/07/2019

关键点:dfs

class Solution {
    
    List<List<Integer>> res;
    
    public List<List<Integer>> combine(int n, int k) {
        res = new ArrayList<>();
        List<Integer> tempList = new ArrayList<>();
        
        dfs(tempList, n, k);
        
        return res;
    }
    
    
    private void dfs(List<Integer> tempList, int n, int k) {
        if(tempList.size() == k) {
            res.add(new ArrayList<>(tempList));
            return;
        }
        
        // start from next number
        int i = tempList.isEmpty() ? 1 : tempList.get(tempList.size()-1) + 1;
        
        for(; i<=n; i++) {
            tempList.add(i);
            dfs(tempList, n, k);
            tempList.remove(tempList.size() - 1);
        }
    }
}

参考资料:n/a

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

posted @ 2020-03-08 06:41  Jimmy_Cheng  阅读(166)  评论(0编辑  收藏  举报