File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments