1 Star 0 Fork 0

wd6/LeetCode-1

Create your Gitee Account
Explore and code with more than 13.5 million developers,Free private repositories !:)
Sign up
文件
Clone or Download
combinations.py 818 Bytes
Copy Edit Raw Blame History
kamyu authored 11 years ago . Update combinations.py
# Time: O(n!)
# Space: O(n)
#
# Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
#
# For example,
# If n = 4 and k = 2, a solution is:
#
# [
# [2,4],
# [3,4],
# [2,3],
# [1,2],
# [1,3],
# [1,4],
# ]
#
class Solution:
# @return a list of lists of integers
def combine(self, n, k):
result = []
self.combineRecu(n, result, 0, [], k)
return result
def combineRecu(self, n, result, start, intermediate, k):
if k == 0:
result.append(intermediate[:])
for i in xrange(start, n):
intermediate.append(i + 1)
self.combineRecu(n, result, i + 1, intermediate, k - 1)
intermediate.pop()
if __name__ == "__main__":
result = Solution().combine(4, 2)
print result
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/wd6/LeetCode-1.git
git@gitee.com:wd6/LeetCode-1.git
wd6
LeetCode-1
LeetCode-1
master

Search