forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
combinations.py
65 lines (58 loc) · 1.51 KB
/
combinations.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from __future__ import print_function
# Time: O(k * C(n, k))
# Space: O(k)
# 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(object):
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
result, combination = [], []
i = 1
while True:
if len(combination) == k:
result.append(combination[:])
if len(combination) == k or \
len(combination)+(n-i+1) < k:
if not combination:
break
i = combination.pop()+1
else:
combination.append(i)
i += 1
return result
class Solution2(object):
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
def combineDFS(n, start, intermediate, k, result):
if k == 0:
result.append(intermediate[:])
return
for i in xrange(start, n):
intermediate.append(i+1)
combineDFS(n, i+1, intermediate, k-1, result)
intermediate.pop()
result = []
combineDFS(n, 0, [], k, result)
return result
if __name__ == "__main__":
result = Solution().combine(4, 2)
print(result)