You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: notes/backtracking.md
+8-13Lines changed: 8 additions & 13 deletions
Original file line number
Diff line number
Diff line change
@@ -54,18 +54,12 @@ def factorial(n):
54
54
55
55
Let's trace the recursive calls for `factorial(5)`:
56
56
57
-
1.**Call**: `factorial(5)`
58
-
- Since $5 \neq 0$, compute $5 \times factorial(4)$.
59
-
2.**Call**: `factorial(4)`
60
-
- Compute $4 \times factorial(3)$.
61
-
3.**Call**: `factorial(3)`
62
-
- Compute $3 \times factorial(2)$.
63
-
4.**Call**: `factorial(2)`
64
-
- Compute $2 \times factorial(1)$.
65
-
5.**Call**: `factorial(1)`
66
-
- Compute $1 \times factorial(0)$.
67
-
6.**Call**: `factorial(0)`
68
-
- Base case reached: return $1$.
57
+
- Call `factorial(5)` and compute $5 \times factorial(4)$ because $5 \neq 0$.
58
+
- Call `factorial(4)` and compute $4 \times factorial(3)$.
59
+
- Call `factorial(3)` and compute $3 \times factorial(2)$.
60
+
- Call `factorial(2)` and compute $2 \times factorial(1)$.
61
+
- Call `factorial(1)` and compute $1 \times factorial(0)$.
62
+
- Call `factorial(0)` and return $1$ as the base case is reached.
69
63
70
64
Now, we backtrack and compute the results:
71
65
@@ -134,6 +128,7 @@ DFS(node):
134
128
Consider the following tree:
135
129
136
130
```
131
+
Tree:
137
132
A
138
133
/ \
139
134
B C
@@ -149,7 +144,7 @@ Traversal using DFS starting from node 'A':
149
144
-**Move to 'D'**, but as 'D' has no unvisited neighbors, **backtrack to 'C'**.
150
145
-**Move to 'E'**, but since 'E' also has no unvisited neighbors, **backtrack to 'C'**, and then further **backtrack to 'A'** to complete the exploration.
0 commit comments