Backtracking Flashcards

(6 cards)

1
Q

What is the pattern and when is it used?

A

Explores all possibilities, backtracks when invalid.

Use Case: Combinatorial problems, permutations. Example: [Generate Parentheses]. Action: Verbalize use case aloud.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the key steps?

A
  1. Choose option, recurse.
  2. Explore valid paths.
  3. Backtrack if invalid, undo choice.

Action: Explain steps for [Generate Parentheses] aloud.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How does it apply to [Generate Parentheses]?

A
  • Problem: Generate valid parentheses combinations.
  • Approach: Recursively add open/close, backtrack if invalid.
  • Action: Verbalize solution logic aloud.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are the complexity and gotchas?

A

Complexity: Time: O(4^n), Space: O(n).
Gotchas: Invalid combinations, stack overflow.

Action: List edge cases for [Generate Parentheses] aloud.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Provide a code example.

A

```python
from typing import List

def generate_parenthesis(n: int) -> List[str]:
result: List[str] = []
def backtrack(current: str, open_count: int, close_count: int) -> None:
if len(current) == 2 * n:
result.append(current)
return
if open_count < n:
backtrack(current + ‘(‘, open_count + 1, close_count)
if close_count < open_count:
backtrack(current + ‘)’, open_count, close_count + 1)
backtrack(‘’, 0, 0)
return result
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Visual

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly