[Lintcode]152. Combinations/[Leetcode]77. Combinations
Posted siriusli
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Lintcode]152. Combinations/[Leetcode]77. Combinations相关的知识,希望对你有一定的参考价值。
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,4],
[2,3],
[1,2],
[1,3],
[1,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, n, k):
return list(combinations(range(1, n+1), k))
2.Recursive - AC in 76 ms
有点像动态规划
class Solution:
def combine(self, n, 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, n, 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, n, 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,就提前舍弃。
以上是关于[Lintcode]152. Combinations/[Leetcode]77. Combinations的主要内容,如果未能解决你的问题,请参考以下文章
1286. Iterator for Combination
leetcode1286. Iterator for Combination