zoukankan      html  css  js  c++  java
  • 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/

  • 相关阅读:
    luogu4781
    luogu 4933
    luogu p1726
    bzoj2238
    luogu 1462 通往奥格瑞玛的道路
    noip.ac 3276 矩阵
    luogu1144
    noip.ac 3248
    奶牛比赛
    小P的Civilization V
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/12440849.html
Copyright © 2011-2022 走看看