You are on page 1of 13

Recursion 2

Good
morning

Contend

01
Quizzes
02 Tower of Hanoi pure recursion
03 Generate parenthesis Backtracking
void solve int

if N ol return I

2 lol
solve N 11 solve i

print NI 3 Solve l 123

solve at 12
3
solve 31 12
Ans 1 2 3

73
02 void solve int NI
if N ol return I solve lol I

print NI 2 solve it 123

solve 21 123
Solve N 11 3
solve 131 123
3

Ans 3 2 1

03 void solve int NT


if N ol return I i
solve 51 123
print HI 2
solve 41 123
solve N 11 3
solve1 31 123
3

As 3 4 5 stack overflow error


105 106 calls
n

Output 1 A C
n 2

I
2

1 A B

2 A C

1 B C

output 1 A B
2 A C
1 B C
Ed's
3

3 A C

i B A
2 B C
I A C
xdisk .IT

01 Move n t disks from A B

02 Move N disk from A C

03 Move N t distis from B c


void tone int n I B

it n 0 return

Tom n t A C B

print n a c

Tom n t B A C

Faith Recursion is to move n t disks


going
from src dest with the helper tower

minimum all the


in steps following
lonstraints

our tree better


Just to create

left call tote n t srs dest helper

all Tom dest


right n t helper src

print n src dest


TOH 3 is I

the É Tone 2 BEE

to tomf1 sc I to ÉI

0 I.C B ytoH O.sB A ono.ae OH


YE.sn
TOH 0 C B I Tomfo C 7

Tony B.CI
1 A C

2 B
ton GB Tomfo B
1 C B
3 A C

1 B A

2 B C

I A C
1 2n
si O n

8 09 AM 8 19 ATT
Q print all of length 2H
validyndparanthesis
for a
given value
Equal no of opening

closing brackets

N I I C

N 2 111 747 1771 1 C

N 3 71 17 7 11 17 111
7 11

Idea I'll build the of 2N


string length checking
it it is valid or not while building it
As state from which
soon as we
get a

we can't valid answer will


get our we

back track

Words expressed
as Branches

Find AIM
BF to find Aim Generate the entire word on one

branch then tompare it with

the given word i.e AIM

Backtracking As soon as see an invalid


you
character with
you return back
exploring that branch further

ten D

een 1 I f closing open


invalid

C 11 C 7

f open n
l
at Cisc is

invalid
void main 1

recur N O 0

void rear str int N int open int close


string
it str length 2H12
print Str
return
3

it open N 14
recur Str N 1 close
open

if close open

recur str l N open close 1

TC 2n
SC O n
f x.nl

it n ol ref 1

else if n 2 of ret f
els

Bits 1

sort A
target

Alex
4 1

S S
Is 1

times

Alen 0 4 4 8
I
9
Sam s
Alex 0 4 31 4 28 9
Sam S S S S S

some

1 2 1 2 5 6
10
g
5 6 6 5

You might also like