class Solution:
def combineHelper(self, n, k, cutoff, chosen, res):
"""
@n: original parameter
@k: number of elements to choose
@cutoff: cutoff from last round
@chosen: results so far
@res: a vector to store results
"""
if (len(chosen) == k):
res.append(chosen.copy())
return
for num in range(cutoff+1, n+1):
# choose
chosen.append(num)
# explore
self.combineHelper(n, k, num, chosen, res)
# unchoose
chosen.pop(-1)
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
chosen = []
res = []
self.combineHelper(n, k, 0, chosen, res)
return res
Note the cutoff condition in the for loop. Still need a cut off variable to record last chosen and control the range of the for loop.
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.