Fork me on GitHub

Combination

The brutal-force way to calculate all the combination.

Linkage

https://leetcode.com/problems/combinations/description/

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
ret = []
self.add(ret, 1, n, [], k)
return ret

def add(self, ret, start, end, item, residual):
if residual == 0:
ret.append(item)
return

for i in range(start, end-residual+2):
new_item = item[:]
new_item.append(i)
self.add(ret, i+1, end, new_item, residual-1)