forked from qiyuangong/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path077_Combinations.py
43 lines (38 loc) · 1.22 KB
/
077_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
class Solution(object):
# def combine(self, n, k):
# """
# :type n: int
# :type k: int
# :rtype: List[List[int]]
# """
# res = []
# candidates = range(1, n + 1)
# self.get_combine(res, candidates, [], k, 0)
# return res
#
# def get_combine(self, res, candidates, prefix, k, start):
# # recursive
# if k == 0:
# res.append(prefix)
# for index in range(start, len(candidates)):
# self.get_combine(res, candidates,
# prefix + [candidates[index]],
# k - 1, index + 1)
def combine(self, n, k):
res = []
self.get_combine(res, [], n, k, 1)
return res
def get_combine(self, res, prefix, n, k, start):
# recursive with only one array
if k == 0:
res.append(list(prefix))
elif start <= n:
prefix.append(start)
self.get_combine(res, prefix,
n, k - 1, start + 1)
prefix.pop()
self.get_combine(res, prefix,
n, k, start + 1)
if __name__ == "__main__":
s = Solution()
print s.combine(4, 2)