zoukankan      html  css  js  c++  java
  • [LC] 77. Combinations

    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],
    ]

    Time: O(C(N, k))
    class Solution:
        def combine(self, n: int, k: int) -> List[List[int]]:
            res = []
            start = 0
            my_list = []
            self.dfs(n, k, 1, my_list, res)
            return res
    
        def dfs(self, n, k, start, my_list, res):
            if k == 0:
                res.append(list(my_list))
                return
            for i in range(start, n + 1):
                my_list.append(i)
                # need to use i + 1 instead of start + 1 for the next level
                self.dfs(n, k - 1, i + 1, my_list, res)
                my_list.pop()
    class Solution {
        public List<List<Integer>> combine(int n, int k) {
            List<List<Integer>> res = new ArrayList<>();
            helper(res, new ArrayList<Integer>(), n, k, 1);
            return res;
        }
        
        private void helper(List<List<Integer>> res, List<Integer> list, int n, int k, int start) {
            if (k == 0) {
                res.add(new ArrayList<>(list));
                return;
            }
            // need to go deeper based on current i and ignore the previous result, so that use i + 1
            for (int i = start; i <= n; i++) {
                list.add(i);
                helper(res, list, n, k - 1, i + 1);
                list.remove(list.size() - 1);
            }
        }
    }
  • 相关阅读:
    PHP和Ajax设置页面请求超时
    Flex 布局教程
    数据库访问优化法则
    phpcms网站搬家至服务器
    phpcms网页替换验证码及搜索功能
    php判断手机段登录
    php环境搭建
    ThinkPHP框架
    JQuery事件
    JQuery
  • 原文地址:https://www.cnblogs.com/xuanlu/p/11669393.html
Copyright © 2011-2022 走看看