Skip to content

Commit 656e3b4

Browse files
committed
Combinations solution
1 parent 0df78b2 commit 656e3b4

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

77_combinations.py

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
class Solution(object):
2+
# def combine(self, n, k):
3+
# """
4+
# :type n: int
5+
# :type k: int
6+
# :rtype: List[List[int]]
7+
# """
8+
# res = []
9+
# candidates = range(1, n + 1)
10+
# self.get_combine(res, candidates, [], k, 0)
11+
# return res
12+
#
13+
# def get_combine(self, res, candidates, prefix, k, start):
14+
# # recursive
15+
# if k == 0:
16+
# res.append(prefix)
17+
# for index in range(start, len(candidates)):
18+
# self.get_combine(res, candidates,
19+
# prefix + [candidates[index]],
20+
# k - 1, index + 1)
21+
22+
def combine(self, n, k):
23+
res = []
24+
self.get_combine(res, [], n, k, 1)
25+
return res
26+
27+
def get_combine(self, res, prefix, n, k, start):
28+
# recursive with only one array
29+
if k == 0:
30+
res.append(list(prefix))
31+
elif start <= n:
32+
prefix.append(start)
33+
self.get_combine(res, prefix,
34+
n, k - 1, start + 1)
35+
prefix.pop()
36+
self.get_combine(res, prefix,
37+
n, k, start + 1)
38+
39+
40+
41+
if __name__ == "__main__":
42+
s = Solution()
43+
print s.combine(4, 2)

0 commit comments

Comments
 (0)