1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution(object): def combine(self, n, k): """ :type n: int :type k: int :rtype: List[List[int]] """ self.result = [] temp = [] self.combineHelper(n, k, 0, 1, temp) return self.result def combineHelper(self, n, k, length, num_now, temp): # print 'start', temp, list_num, length, self.k if length == k: # print 'add', temp self.result.append(temp[:]) # 这里直接写temp,就会导致result内的temp永远是一个实例,后面修改temp会使得result一直在变化 # print 'result', self.result return for i in range(num_now, n+1): temp.append(i) self.combineHelper(n, k, length+1, i+1, temp) temp.pop()
|