zoukankan      html  css  js  c++  java
  • Combinations

    DFS

     1 public class Solution {
     2     public ArrayList<ArrayList<Integer>> combine(int n, int k) {
     3         ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
     4         if(k == 0 || n == 0)
     5             return res;
     6             
     7         ArrayList<Integer> output = new ArrayList<Integer>();
     8         generate(1, n, k, output, res);
     9         return res;
    10     }
    11     
    12     public void generate(int depth, int n, int k, ArrayList<Integer> output, ArrayList<ArrayList<Integer>> res){
    13         if(output.size() == k){
    14             ArrayList<Integer> tmp = new ArrayList<Integer>();
    15             tmp.addAll(output);
    16             res.add(tmp);
    17             return;
    18         }
    19         for(int i = depth; i <= n; i++){
    20             output.add(i);
    21             generate(i+1, n , k, output, res);
    22             output.remove(output.size()-1);
    23         }
    24     }
    25 }

    Recursion

    public class Solution {
        public ArrayList<ArrayList<Integer>> combine(int n, int k) {
            return helper(1, n, k);
        }
    
        private ArrayList<ArrayList<Integer>> helper(int start, int end, int k) {
            ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
            ArrayList<Integer> re = new ArrayList<Integer>();
            if (end - start + 1 < k || k <= 0) {
                result.add(re);
                return result;
            }
            // add all to the re
            if (end - start + 1 == k) {
                for (int i = start; i <= end; i++) {
                    re.add(i);
                }
                result.add(re);
                return result;
            }
            // include start
            ArrayList<ArrayList<Integer>> tmp = helper(start + 1, end, k - 1);
            for (ArrayList<Integer> r : tmp) {
                re = new ArrayList<Integer>(r);
                re.add(0, start);
                result.add(re);
            }
            // not inclued start
            ArrayList<ArrayList<Integer>> tmp2 = helper(start + 1, end, k);
            result.addAll(tmp2);
            return result;
        }
    }
  • 相关阅读:
    input清楚阴影 number属性
    转 溢出隐藏
    多行,溢出隐藏 css
    JS判断移动端还是PC端(改造自腾讯网) 仅用于宣传动画,下载页等
    项目开发(Require + E.js)
    showPrompt弹框提示
    图形验证码
    CSS常用技术总结!~~
    移动开发常用技术总结!~~
    JavaScript常用技术总结!~~
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3537174.html
Copyright © 2011-2022 走看看