Backtracking Level 2
Backtracking Level 2
↓
Backtracking
Viraj Chandra
&
+ + Java & ↓ - -
f(n) -
fn) + Base
OData-Case
. . . .
~
-
-
-
-
Structure
X
-
The first call is at the bottom of the stack, and the last call is at the top.
- ↑
-
V top of
After a call is executed, it is popped from the stack, and the returned
value is passed to the current top element.
-
E
! f(x )
& Gretu ,
1(3) 1(2) +
+
=
-
=
L v called 2
Sc
-
v
o(X) ↑ 2) ↑ (D) +
↑
↳
-
&
f(1) =
f(0) +
#p
S tack
Y(0) called
15
= # S
=
1
Memory - =
Y
Backtracking >
-
Extension
#- recusion
Backtracking will stop at the first instance where some given condition
is not fulfilled. This process will remove entire subtrees from the tree.
-
K
..
↓ ↑
↓ ↓↓
↑ ↳ NT-
·
77 S
o fn(i coins)
+1 som
,
8 .....
,
& ↓ 't
-
-
/
Ts
9
⑧ : ↑n Litt Sum+ coins
↓
...
I
G
,
purned ⑨
&
I
[i]
/Coin ,
O
&
-
L
-
I
&
& J
-
: 18
·
>
-
3 13 target 7
↳
5, ,
⑮
⑧↳
⑳
Backtracking Example ProblemO(2
- G
-
- -
-
Given N positive coins, find number of subsets you can make such that
the sum does not exceed K.
-
Brute-force will go till the last possible index, and then check if the sum
-
Backtracking will stop at the first index where the sum exceeds K.
- -
-
O
[ I to -istalid
News paper
Sudoku Game >
-
↑
E
G
-
↳
- board
Fill a 9x9 grid with 1 to 9 such that such that each row, column, and
3x3 sub-grids have all values from 1 to 9.
cells V & O T Pruned I
↓
O free
30
9 X9
O
8I
=
.
~ I 235 *
21 to 9]
-
-
-
-
-
000
4 56.
-
·
-
s
④2
/
- -
Or s
-
In [I to 93 ↑
J
every
row comm only 000 ·
-
-
>
Once
② 2011 11 -
-
In &
-
H
-
-
every
I I I
I
·
"I'l
-
↑T
T subgrid 9
T
In 3X3
·
way /
O I
- - -
I
↑N + #
mind
-
-
999
-
⑩
- -
T
na
L
Fl F2 #3
V
~
9
so ↓
9 -
B Tracking
-
o
L -
I
O
G
>
-
--
i
O
=
, >
-
=
F8 *
O
i
is =
=
To
9
.
↓&
5
de
>
-
&
-
>
I to 9
O
=
= S &
>
-
-
C =
G
=> -
-
>
- >
- -
E
Chess-Queen
N-Queens Problem
⑪
such that none of the queens attack each-
Given an NxN chessboard, find the number of arrangements of queens
other.
⑭ >
- ④
-
·
Problem Solving:
• https://leetcode.com/problems/sudoku-solver/