0 ratings 0% found this document useful (0 votes) 3 views 20 pages Recursion Notes
The document discusses recursion, its definition, and its applications in solving computational problems. It includes examples of recursive functions for tasks such as calculating factorials, Fibonacci numbers, and checking if an array is sorted. Additionally, it touches on concepts like dynamic programming and space complexity associated with recursive algorithms.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Go to previous items Go to next items
\ Lerabion . .
concep) required Yor recursion
2. Functions
Use of Recusionts
Wees
Graphs
Oynamic Programming .
bottom be uy bolukion comiine)
po Down (towerds Base cose)
€:9. Fa con'al
nlc WxCn-\) xGy-29 Xn-9% 4
Fo) = Gey> ren ese seey 4 ERE
iF xe Co ected 2
2 6X 4x zx Ley
What is Retursion i=»
Using math -
ton:
Forys 2724 See svavier!
FE Crea) = G2 = ls Cs sega ervey xhe)
= @ | ne so
pase case. ey \evel smmal\\er prbum
Sa know = ol =) similay Junckon
Recaslve Funckion.
Recursion »-
Recursion 15 Method of ‘selving a computotionol
problem where She soluton depends on solution te smalley
instance of She samme prblem
(mp yo Know = base case.
nd!
peal Nae
main Fun main fan — Fan 9 Fun fun
rc KIN RH her
Voliun ir Yay (Yale Mtge
retary core.sleps in temaston: +
\. Base case
2 wok Cary)
3. call inne Function eg. ¥ (nt) CACEAT “GMAT inner
Hany any Hwy)
“
Fon). By Bony
Pncipal of Mothematical inducion CPME)
assure 1 -
a (2H) Selution cored SmT
Problem 4
Print number From on tol (decreasing order)
\sel> 5 for loop = for Cink (= mle; ipl sin)
pwn ci)
Ne ve a)
ECRy son ¥ FCnd 5
2A
a 4 Fes)
Solukon® -
F Cink nj
print Cn) 5
FoCm-) 5 Gaga can At Fecintn)} < inner Fancion
ae] Fey Bare care (RA 0 BY of arm aie)
public dass Recawion Basic
& public shatic Void prinkDec ( int nD
tik eed 1@® Bue datine
& sop om; N® » value SY pani-araiay
rhe 5 1@ «hu
soy (nt 7795 1O 9 value AY PANY BHATT
print dec (NAD) IBnner Fane RY ca\reaset
4
psyen C9
ink ne lor sey et a Boney
print pec CD) I main YX task rar Fanconiad eprpec BVT 9 \Gimeeyy
galt slack 424 retme o Lehner
‘ ¥
Cdenetbec ty Lae ata at
Ld inter 1 4 ae -
sf ypanltec nT n aT
ginidec 8B 4
yanibeo h 4 |g
stp Dec n=tol to
Q
’ FC Way parareber Baa cae}
wremory Be HET
1 individaol parameler memory high matty aY site wy areoy
(In Keation Finches
2. Yoo rrany calls.
3. Bare Cose sony AY shack oveHow
-
@
(Dobler >
punt namber Frome ntel Cncreating ord)
Fond: Ftnad th
Fores FOn-2) 4 Fon)
peblic clos Recanmion Basis
3 public stakic void pant Dec C in}n)
i} est)
I @ Bose wore
© sep nds 1 ® Qeoraition tue BAC OMIT
aehuvn } W® wiuw rekurn ea
4
guintine On) WO woes lane A cat
eevee Gn) tec e10),) 1@® priny
psu ()
5 ink ne
print In lo) }call shack
wk oO} th conditon Reet harm
ernent
a .
4 PE
Ant
aa can Fromes
main
©
eeeetne)
punt Facloria) of number
nls ne (M-rvSt
Fond: ny fond
\
= Fon-1¥ £ yr)
Fad Cnty L
ck Gn OSs pase case it(me=0)
Fu-\ = Fad Hadi S veka 15
Fue wx Fonds i
athurn FN
3
public clats Recursion Beste
{ puvlic shatic wih int fact dint)
{ \pdeaeet =
if n= 20) W@ bore Core
4 eta 1® yew \ elo =
4 ves a if you wont Whi -) fer negah=
nares
yw) Trm\ = Fach one) > 1@ env fado-d
ink Tr = nk Fad (nds [® ime vxtorr
‘ teluyn Fy ea
psym CY
{ inl ness
soy ( Fach On) 3
%‘i 4 thus n
COM shack + Tlyed Keele, ifn ce torditentus thu
cen ru Ted
ay ( :
eS Tran .
C\iGEn Mme a(n)
( | Commpleyihy
Gay Fou lL é
\ Space \
|seomeescity of)
—t
Lime complenity pony > on call RAH
Sta compbrity= ol): cab shack Ga ET level Uo Variable
a gy ar.
problem 4
[Grstant eee |
punk of sum of Kish n nahuva) numbers
Foy = nd Fura)
eg. Fes) = Sy Fc «fio.
2
44 £03)
eto’
\
SS
wa FOYE pee come
In} sum Cin}en) {
> Bare case Uf Cnen
Sm-\ - sam (n-1) wthan!.
$M = ny fy) 5
thn syCiede |
yublh. clans Retars{onBaaic
XL public shatic Ink Baa (aleSum (intn)
QE U Ric = 0)
4
3
in) sumi- calSum On-l) 5
AY Sh:
whut |
nt SNm)
yelum sn}
sum ()
Any eon
4 SoP ( Calsum(n) ),
th (wes) toncdliNo me
“Wene comm pleryciy = och)
SPA Compbarcthy = oth)
cast Frum,
punt NY Fibonacci. Number
OV, N,2,3,5, #, 1351
we
Fibnya = Fiby + Fibony
Bib
Vibra Ss Fein)
Fibr = yy + Fiby
\
be © Bay ayy
Nate + ih Fib fy: 07
a hewe case Bbagey jrhin
Veeaativag 7Viby: Wena } Heyer
Ying Fey t Fiba o— ~ tea a)
toy @ re.
.o9 ——»
(ofibs ¥ Way ae
Yo we Coy
Fee FEO 2
. ate io eo)
oe a) wy
Fis yd Fibeoy
ay lo)
Vie Cink) ¢ ' elu,
- + Base care Wfn-=0 2O
neni 313
| Fibw-ys Hb (nad
Fibn-t: Fibcn-vd
Fibn : Ren iapds Fen a
| athan Rpw
public class Recent sionRBass «
on
public stake
Wone=B Won ‘>
| warn ny
| j
Rb Gravy
Fip (net) |
ink Fibnml
| in) Fibwm? =
ind fn = Pam ¥ Enema}
3 retuy fy
gsr 7
A intnes;
Sop CHD ONY)
a a
iny Rb © tn)S A Gr Abe)
space complexity 2 0 (n)
Kime Complxihy = 6 GP) S nes
PA Ponenbiod iN
ney 823 G)
NIN
Wey Ren Her hay (8)
WXVLVS NN
Ce
{yropums
dreck tka given array is sented ov ok nts Ger, ——
ecawny tidaes
\ a 5 4S atid <'acity
tooth OS
Te (uot on
tompare-
sorta = alo} < 4017 } Sorted yy
(5 Sorted Cink aca, inti)
a Bore care f= aw length-)
MVD C= ase Cin)
issoed Cam, S495WHC dan RecauionDeme
4 TeMic shaic boolean isSeted (inl ar), ini)
Vy (i= = ayy. Vength 1)
g yelurn hues
3
W Cary iy > ayy Cit)
4 velurn False}
rehayn isSouhed Caw, 413
4
sym C)
Ot com 711.2,3,5,53 Ni Neuse
Int avr 1 = £5463 Le
int aw = 43 H Yau
intiaw (32 G1,9,4,5,39 II False
sop (isSoted Camry o)) 5
’ i
stad analysis - \ L525 344
Ye Eh is ave 1171 w/
iG oe
end 4
ae wf fos train a }
Aime complexity ow)
space Complexity - © Cn)
Sr G4, 5.3543@
\neblerm 7]
WA fo Rnd the Fish 6 carence ofan dlementin an
ares
[aa les later
yo | + 3 4 5 «7%
xekurn
it s aden) = ie Bent
we) ether
public closs RecurssronDemo
ae
public sholvc ink FrnbOccarang Cink ave C}, int Fer ink)
{iF Cie = aw length >
a.
3
ik Car CiQ= = ket)
g
whurni
3
anhurn FistOcurence Carer, in):
3
poy
S awh aw $Gi3, raiser re 51355
gop Ferrer Se) >
Sop ( Finhoccurany Carri s 03) 5
3 s
Stack Anolysist-
ee
eee
hone < \
OF fancHony me compirhy of)
Space Compasty Or}®
[pester 8]
WAT to Find the last occurence of an element} in an ana,
3 ; ey era
wer USS LAU s Delay
a \eo 1-4 ‘77
Compare with seh \ Look fensard -
| \s lock Forward | ee ee
i Fin) Ocurence 7 ~ Los} oquevente.
public class RetarsionDemo
&
public shakic int loskocuermes (int ary 00, int key, ints)
A tees anetength)
{yearn = 5
3
:
Tat isfound = lash Ouuerence Carn Fey, VY)"
if Cisfoand Y= -D
{ velar tsfound j
4
Hdheckwith se\t
iF Gyr Cid ee Fey)
Aas 1s
int isfound: let ocuerence lary skey. itt)
w
iP Gsfound == 4 5 Oneiy == key)
{veh 1
athum tou nds
4
pee >
imtJan: LSS 554) 9)
Sey (Noh Cuurence $0)2h 2 2¥2v22
nelurn % K port
[fable a)
prin) 2”
a
4
ayxr? Ses wy eae
» -
reay? : Syn
saxon ix?
power (aH) YZ — Porsere
— ——————> Baxtore - N=0 Wehirn ml
Cernay
public class RecurssVonDemo
t Poble static ink Power (inky, int)
iF (ne et)
&
rehurn 1h
“if enmis power Cr, nay;
roink om =
( > AK enml;
lt whan in)
Yelarn veg power (x nV);
4
ese)
§ Pe sop ( power Q)8))s
4
for
ow
Bn
=
- ;
us eee | ee¥
whew 16)
print ¥™ on Ghtegn)
ty Ave 2 ah yy
No en
gas.
: 2
ay Peerage
n- odd
awatert
Public dots Power
Lo public shadte ink opkimised Power [inta , intn)
7 hol fpower $q== Oph mise d Power (2, h/2)) 7 Optivn sed Posey (4,n/3)
sce Linear oun)
ies tht S=0) an
ed
© Wali powersg = a half Pouersa [int halfponer ophes
Power (gn)
4 [Int hatfoweviq.- halt peuer
aha halt PowerSq, 5 halt poue
5 Nac ophimiredPoucy
/ Fan chior ory tai
ec Uneay ar By RL
& jphast Walfyowey vanabl
ink nh =to,
2 $00 fophmued Power (and) 5
Square Tae
)
°
Cs VERT and Gay
eqn) =(os
{Problers 11]
Ving Problem
Ginen a 24m" board and Wie of s\2© 2417 rouy,)
the number of way te tile and given board wing ay
piles (RM Con either be placed horhonbelly oF
vertically)
i
eae LENTZ, —
4 3
S| TO
2 (oe —| {|—
. : @
NeMile-y waysea
\ bore cores.
neo 2x0 wos)
net aX easy [J
netoae) ees te TT)
nz3 2%3 woye? = it) te) Ee
Choice:
vertical place |
2. Horhrortally plaw
HM Ux hW-1
== 7
\ i Fina) ce) ry
| A Fond 2x Fanety: te one?
< = ay Ftd: oxen iy
koay >
Von) ante = vernal y fF Cn)eS cal 3) Hovitan\al:
Fond 2H
==
i
es)
j Font). Bera
= henzontal + ¥ Cnt)
Barc case Doo
Folad ways bonny SF On-2)
Public class Recursion Dero
public det stoke inh hiingProblrm Cntr) I 2 en(toersas)
Nvcerdicod Shove
inl fant WlingPreblem Cn y's
wh F '
Ji podronte) cheite
(nk fnm2 - dling Problem (ro):
1) Poel Wey
Joint Pohaways = Ten) | tant
4 yelurn foblal 045
gym
V sop CHiling haber 1) Hea)
5
Dynami: Programming’. (DY
same ansuter stored wm wht
ophmsied solatienay
Cinbtow try a
Remove Duplicate in Strings —e (a-2> fA~7) | @-4¢
Hoshi rct
“appranacellege!’
“fapncoleg”? < unvqut chavacers
o Dewshing CsB)
@® jax string inden
@ mop Cbeclean) array. [qT rm
™OP Chootean) oe
type Convention in expraston—> int
chay
Coa
a a indax : carr chay = 4a”
Bing? = \ (may)
ea as,
Base 2
eG te aS stadengih
Koam = +i true 3 Neo SX
Char 4 present in map Woe eo ma Rete
jax oe jawed 5 Fdsryes FUdxd+\
poddic lous RevassionDemo
2 gublic skate void FernoveDaphicate (string she, ink idx, shringhaiche
new Shy, boolean map )
fe (ax- shtength OY
{Sop (new Str)
aren |
[karan
char curr Char = ste-char A} Cidy) | |
vb Grnap | ture tray ~ £47] == rue) |
L paugiicoke |
vemere Duplicate (shy idaty, newsh, map) |
% else |
L maplrunchar fa) -2ne
‘ vemove Dapliceake Cafe, WAY, new SW -cippend (ery Cher), map 3pym 0)
Seana shy
Caygnna college
Temmeve Duplicobes (she Of Being Baildes nee bewlean 2a)
Friends Raiving Problem
Given 1 friends, each one can Yemain singl, oy can be
paired up with some other Friends ach bhends can be paired
Find ouk tre Yolel number of Ways tn which
Friend: Can Fmain single or can be
ony once
paired uy.
Gy baends Sok wo ogy a nay
>» pair
mien Ri arngks — weasgys =)
cia a,b + ras 22
woos
& & Cape yair
Owe Singh
ne RAK aoe be pare wayse G
Gacy a: pair
< lash) ab pair
Ohare case n-\ wos
Wer woys 2
© keam Yoh ways Foray + Gn Fans)
Chole
GG gary
te) ny
a (Had x F en)
a Cede) Cab) Eer died
a) Cle aied
Chadd Corey
tae)
wicrddpublic loss Recursion tere
& gaatie svae tH BendBaring Cink *)
Cwes ty Wrest)
Lahm ny
3
I} single |
in} Frenmt> Wendy Paving tnd if
{P poir
ink Ene tz Tiends Paiving (n-2) ;
ny palyWay? (nr) te Frm?)
i oh\Woys |
ny Sdhlays 2 Trem 14 BpairWoy 5 \
neharn Sol Woys5
4
svn C)
Terends Pairing 639)
aetkurne Friends Pasen gs mr o-0*
Friends Paving (2) 5
4
yarn 14)
cour 14)
i
fainany Shing Prblern
prinle all binany strings ot size N withouk consecutive One
Bue Cue
Heo |
hes 1 OO
nt OO
oD |
ot or
1.007\ L 5
vi
6 wry plau
4 Fon
(onl plae
decision
parlic dass Recars on Derne
4 . on
T paste shah void prinbBin Shings (ink n in) 05h Place Sheer)
Q yb reo)
X soy Caos
Te Costplace == 0)
Isi¥ 0 ow chain n
\ parh slat weit
prin} Bin Swings Cd, ©, sheaplend £70"9);
| want Bin Stings CHA, 1, Sh ee
i 4
| Barge
, | 4 prinhbin sings (nv, os Sevappend ae
( prinkBinsirings (nal, Oy Se aprend (*0");
Sf Clostptace ==)
”y);
prmbbinstings (nal, 1, sh-appena cae):
3
Bs
evn
£ paid Bin sarge OF | reer Shrmgiestdes (7 1)
5— Upeo [ooo a= Bae Cov.
ovo < ‘000" 5
Onan
TRO | G00” 26
“ rere's ° ol
o\o . nea. Ltre|“o” 4
nea Lpsoleers ae
Pain ny Ute |
ooo
col
O10
joo
lol