Key Idea
- Pass
start
and path
to DFS().
start
denotes the index to start exploring from, initialized to 1.
- It increments with each recursion to avoid reusing elements.
path
keeps track of the current permutation being formed.
- The escape condition triggers when the length of
path
equals the desired combination length k
.
- After each recursion, use
pop()
to backtrack and explore other combinations.
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
def dfs(start, path):
if len(path) == k:
result.append(path.copy())
return
for value in range(start, n+1):
path.append(value)
dfs(value+1, path)
path.pop()
result = []
dfs(1, [])
return result