加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

[Lintcode]152. Combinations/[Leetcode]77. Combinations

发布时间:2020-12-14 04:24:33 所属栏目:大数据 来源:网络整理
导读:152. Combinations/77. Combinations 本题难度: Medium Topic: Search Recursion Description Given two integers n and k,return all possible combinations of k numbers out of 1 ... n. Example Given n = 4 and k = 2,a solution is: [ [2,4], [3, [2,3

152. Combinations/77. Combinations

  • 本题难度: Medium
  • Topic: Search & Recursion

Description

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

Example
Given n = 4 and k = 2,a solution is:

[
[2,4],
[3,
[2,3],
[1,2],4]]
Notice
You don‘t need to care the order of combinations,but you should make sure the numbers in a combination are sorted.

我的代码

class Solution:
    """
    @param n: Given the range of numbers
    @param k: Given the numbers of combinations
    @return: All the combinations of k numbers out of 1..n
    """
    def combine(self,n,k):
        # write your code here
        res = []
        s1 = [[]]
        s2 = []
        for i in range(1,n+1):
            while(s1):
                tmp1 = s1.pop()
                tmp2 = tmp1+[i]
                if len(tmp2) == k:
                    res.append(tmp2)
                else:
                    s2.append(tmp2) 
                if k-len(tmp1)<=n-i:
                    s2.append(tmp1)
            s1 = s2
            s2 = []
        return res

别人的代码

https://leetcode.com/problems/combinations/discuss/27024/1-liner-3-liner-4-liner

1. Library

from itertools import combinations

class Solution:
    def combine(self,k):
        return list(combinations(range(1,n+1),k))

2.Recursive - AC in 76 ms

有点像动态规划

class Solution:
    def combine(self,k):
        if k == 0:
            return [[]]
        return [pre + [i] for i in range(k,n+1) for pre in self.combine(i-1,k-1)]

3.Iterative - AC in 76 ms

class Solution:
    def combine(self,k):
        combs = [[]]
        for _ in range(k):
            combs = [[i] + c for c in combs for i in range(1,c[0] if c else n+1)]
        return combs

4. Reduce - AC in 76 ms

```python

class Solution:
def combine(self,k):
return reduce(lambda C,_: [[i]+c for c in C for i in range(1,c[0] if c else n+1)],
range(k),[[]])```

思路 我当时的想法是,对每个元素,有可能存在或不存在于某个结果中。其次,如果最后余下对数均加入一个结果中仍不足k,就提前舍弃。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读