Skip to content

Instantly share code, notes, and snippets.

@nma
Last active April 5, 2019 04:37
Show Gist options
  • Save nma/986efdb9c348b0d3b28cf6afff6fe0b8 to your computer and use it in GitHub Desktop.
Save nma/986efdb9c348b0d3b28cf6afff6fe0b8 to your computer and use it in GitHub Desktop.
Combinations Backtracking
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
nums = list(range(1, n + 1))
combinations = []
def backtracking(results, path, depth, options):
if depth == 0:
results.append(path[:])
else:
for index, num in enumerate(options):
path.append(num)
backtracking(results, path, depth - 1, options[index + 1:])
path.pop()
backtracking(combinations, [], k, nums)
return combinations
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment