[Lintcode]152. Combinations/[Leetcode]77. Combinations
152. Combinations/77. Combinations
DescriptionGiven two integers n and k,return all possible combinations of k numbers out of 1 ... n. Example [ 我的代码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. Libraryfrom 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 msclass 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: 思路 我当时的想法是,对每个元素,有可能存在或不存在于某个结果中。其次,如果最后余下对数均加入一个结果中仍不足k,就提前舍弃。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |