Skip to content

Commit 2176a56

Browse files
committed
组合
1 parent 61840b8 commit 2176a56

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

combinations.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class Solution:
4+
"""
5+
@param n: Given the range of numbers
6+
@param k: Given the numbers of combinations
7+
@return: All the combinations of k numbers out of 1..n
8+
"""
9+
def combine(self, n, k):
10+
# write your code here
11+
# TODO: 添加注释
12+
list = [x + 1 for x in xrange(n)]
13+
return self.dfs(list, 0, k)
14+
15+
def dfs(self, list, pos, k):
16+
n = len(list) - pos
17+
if (not list) or (n < k):
18+
return None
19+
ret = []
20+
if k == 0:
21+
return [[]]
22+
elif k == 1:
23+
for i in xrange(pos, len(list), 1):
24+
ret.append([list[i]])
25+
return ret
26+
else:
27+
for i in xrange(pos, len(list), 1):
28+
combs = self.dfs(list, i + 1, k - 1)
29+
if combs:
30+
for comb in combs:
31+
new_comb = [list[i]]
32+
new_comb.extend(comb)
33+
ret.append(new_comb)
34+
return ret

0 commit comments

Comments
 (0)