zoukankan      html  css  js  c++  java
  • 77. Combinations变形,还加了字母

    Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

    You may return the answer in any order.

     

    Example 1:

    Input: n = 4, k = 2
    Output:
    [
      [2,4],
      [3,4],
      [2,3],
      [1,2],
      [1,3],
      [1,4],
    ]
    

    Example 2:

    Input: n = 1, k = 1
    Output: [[1]]

    用字母当数字,输出所有combinations。 例子:假设 k = 4, 输出  ["1111", "1112", ... ,"1119", "111A", "111B", ... "ZZZZ"]

    最直接的方法就是for四遍吧。

    不过肯定要优化:dfs是干嘛的来着?和backtracing有何区别?树的dfs是traverse和dc,图的dfs是traverse和回溯法

    肯定是backtracing

        public static List<List<Character>> combine(int k) {
            List<List<Character>> combs = new ArrayList<List<Integer>>();
            List<Character> chars = new ArrayList<Character>{'1', '2', '3'...'z'};
    
            combine(combs, chars, new ArrayList<Integer>(), 1, k);
    
            return combs;
        }
    
        public static void combine(List<List<Character>> combs, List<Character> chars, 
            List<Character> comb, int start, int k) {
            if(k==0) {
                combs.add(new ArrayList<Character>(comb));
                return;
            }
    
            for(int i=start;i<=chars.size();i++) {
                comb.add(chars[i]);
                combine(combs, comb, i+1, n, k-1);
                comb.remove(comb.size()-1);
            }
        }
    View Code
     
     
  • 相关阅读:
    HTML5标签
    CTF web之旅 45
    CTF web之旅44
    CTF web之旅 43
    CTF web之旅 42
    CTF web之旅41
    CTF web之旅40
    CTF web之旅 39
    CTF web之旅 38
    CTF web之旅 37
  • 原文地址:https://www.cnblogs.com/immiao0319/p/14455573.html
Copyright © 2011-2022 走看看