- Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathcombinations.py
More file actions
Latest commit
36 lines (33 loc) · 1.07 KB
/
Copy pathcombinations.py
File metadata and controls
36 lines (33 loc) · 1.07 KB
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
# coding: utf-8
classSolution:
"""
@param n: Given the range of numbers
@param k: Given the numbers of combinations
@return: All the combinations of k numbers out of 1..n
"""
defcombine(self, n, k):
# write your code here
# TODO: 添加注释
list= [x+1forxinxrange(n)]
returnself.dfs(list, 0, k)
defdfs(self, list, pos, k):
n=len(list) -pos
if (notlist) or (n<k):
returnNone
ret= []
ifk==0:
return [[]]
elifk==1:
foriinxrange(pos, len(list), 1):
ret.append([list[i]])
returnret
else:
foriinxrange(pos, len(list), 1):
combs=self.dfs(list, i+1, k-1)
ifcombs:
forcombincombs:
new_comb= [list[i]]
new_comb.extend(comb)
ret.append(new_comb)
returnret
# medium: http://lintcode.com/zh-cn/problem/combinations/