zoukankan      html  css  js  c++  java
  • Leetcode 77 Combinations (Backtracking)

    Leetcode

    问题描述

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

    例子

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

    方法一

    ** Solution Java **
    ** 1ms, beats 100.00% **
    ** 42.6MB, beats 6.52% **
    class Solution {
        public List<List<Integer>> combine(int n, int k) {
            List<List<Integer>> ans = new ArrayList<>();
            helper(1, n, k, ans, new ArrayList<Integer>());
            return ans;
        }
        private void helper(int start, int n, int k, List<List<Integer>> ans, List<Integer> cur) {
            if (k == 0) {
                ans.add(new ArrayList<Integer>(cur));
                return ;
            }
            for (int i = start; i <= n - k + 1; ++i) {
                cur.add(i);
                helper(i + 1, n, k - 1, ans, cur);
                cur.remove(cur.size() - 1);
            }
        }
    }
    

    方法二

    ** Solution Java **
    ** 3ms, beats 87.78% **
    ** 43.2MB, beats 6.52% **
    class Solution {
        public List<List<Integer>> combine(int n, int k) {
            List<List<Integer>> ans = new ArrayList<>();
            if (k < 0 || n < k)
                return ans;
            if (k == 0) {
                ans.add(new ArrayList<Integer>());
                return ans;
            }
            ans = combine(n - 1, k - 1);
            for (List<Integer> list : ans) 
                list.add(n);
            ans.addAll(combine(n - 1, k));
            return ans;
        }
    }
    
  • 相关阅读:
    路由器端口映射
    字符编码笔记:ASCII,Unicode和UTF-8
    2、Spring之AOP
    八、模板方法模式
    三、装饰者模式
    七、适配器模式
    六、命令模式
    五、单件模式
    乐观锁与悲观锁——解决并发问题
    一、策略模式
  • 原文地址:https://www.cnblogs.com/willwuss/p/12551098.html
Copyright © 2011-2022 走看看