Backtracking
94 / 170BacktrackingLesson 1 of 10About 70 min
Recursion that builds something up and takes it apart again. The undo is the whole difference.
The pop is missing. The base case uses >= rather than ==, which is the only reason this terminates at all. Type what it prints.
def broken(length): results = [] current = [] def explore(): if len(current) >= length: results.append("".join(current)) return for digit in "01": current.append(digit) explore() # no pop explore() return results print(broken(2))Three searches on the same skeleton. all_paths lists every path from the top-left to the bottom-right of a grid moving only right or down, as strings of R and D. combinations_of lists every way to choose exactly k items from a list, keeping the original order. all_splits lists every way to break a string into non-empty consecutive pieces.
Tests
print(sorted(all_paths(2, 2)))print(sorted(all_paths(1, 3)))print(sorted(combinations_of([1, 2, 3], 2)))print(sorted(combinations_of([1, 2], 0)))print(len(all_splits("abc")), sorted(all_splits("ab")))Output
Run tests to see output.
Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.