• 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
     
     
  • 相关阅读:
    Ruby
    WebGL的第二个小程序
    wegGL的第一个小程序
    Node.js介绍
    接口隔离原则(Interface Sepreation Principle)
    参数
    字段/属性
    接口和抽象类
    javascript中的事件
    线性回归算法-4.多元线性回归算法
  • 原文地址:https://www.cnblogs.com/immiao0319/p/14455573.html
Copyright © 2020-2023  润新知