Created
July 19, 2020 23:18
-
-
Save Shaddyjr/ef3ba1ee75ac8d53e29fc179633b83e5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# source: https://leetcode.com/problems/combinations/ | |
class Solution(object): | |
def combine(self, n, k): | |
output = [] | |
stack = [] | |
i = 1 | |
length = 0 | |
while True: | |
# if stack if k long, add to solution (as copy) | |
if length == k: | |
output.append(stack[:]) | |
# if done with stack or out of options... | |
if length == k or i > (n - k + length + 1): | |
if length == 0: # no more options! | |
return output | |
# BACKTRACK | |
i = stack.pop() + 1 # remove tail end and focus on next number | |
length -= 1 | |
else: | |
# stack needs more options | |
stack.append(i) | |
i += 1 | |
length += 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment