码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 77. Combinations (组合)

时间:2020-03-08 10:05:32      阅读:64      评论:0      收藏:0      [点我收藏+]

标签:leetcode   一个   run   blog   资料   code   fast   参考资料   fas   

题目标签: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/

LeetCode 77. Combinations (组合)

标签:leetcode   一个   run   blog   资料   code   fast   参考资料   fas   

原文地址:https://www.cnblogs.com/jimmycheng/p/12440849.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!