Session 6
Session 6
&
BACKTRACKING
PREPARED BY : KHALED EL-HADY
Table of contents
How recursion
02 works ? 05 Intro to Backtracking
03 Why recursion
works ?
06 Problems again !
• INTRO TO RECURSION
- One way to think of recursion is that it’s when a function calls itself.
3
• INTRO TO RECURSION
- Factorial:
- a! = a * (a-1) * (a-2) * … * 2 * 1 .
- Factorial iteratively:
- We can get a! by multiplying all numbers from a to 1. Simply, by making a loop.
- Factorial recursively:
- Another way to solve the problem is to notice that a! = a * (a-1)! .
- We can solve the big problem a! if we solved the smaller one (a-1)! .
- Similarly, (a-1)! = (a-1) * (a-2)! . We can keep going until we reach 1! which equals 1 .
- 1! was our base case which can be solved directly.
4
• INTRO TO RECURSION
5
• HOW RECURSION WORKS ?
- In this part, let’s trace the code to get a feeling of what’s happening.
a=5 a=4
main() factorial(5) factorial(4)
long long a = 5; a = 5; a = 4;
-- Some code -- 5 * 24 = 120 -- Some code -- -- Some code --
4 * 6 = 24
cout << factorial(a); return a * factorial(a-1); return a * factorial(a-1);
a = 1; a = 2; a = 3;
1 2*1=2
-- Some code -- -- Some code -- -- Some code --
return 1; return a * factorial(a-1); return a * factorial(a-1);
6
• HOW RECURSION WORKS ?
• Flow of control passes back to previous scope once function call returns values.
Code
8
• WHY RECURSION
WORKS ?
• Mathematical Induction:
To prove a statement is true for all n. First, Prove it’s true for the
smallest value (0 or 1). Second, Prove that if it’s true for some number k, it
will be true for k+1.
• Recursion Induction:
We know that factorial(1) returns a correct value which is one.
We also know that our recursion step is correct which is
a! = a * (a-1)!
Then, our function must return the correct value for all inputs.
9
• PROBLEMS:
- FIBONACCI
Solution
10
• PROBLEMS:
- PRINT FROM N TO 1
Given a number N. Print numbers
from N to 1 in separate lines.
Solution
11
• PROBLEMS:
- PRINT FROM 1 TO N
Given a number N. Print numbers
from 1 to N in separate lines.
Solution
12
• PROBLEMS :
Solution
13
• PROBLEMS :
- GCD
Solution
14
• PROBLEMS :
- PALINDROME
Solution
15
• PROBLEMS :
- FAST POWER
Solution
16
• PROBLEMS :
Solution
17
• PROBLEMS :
INPUT:
33 Solution
524
135
927
OUTPUT:
24
18
• INTRO TO BACKTRACKING
- A method where you are solving problems recursively and trying to search about
every possible combination to get the desired response to your problem.
19
• PROBLEMS :
Solution
20
• PROBLEMS:
- GENERATING
SUBSEQUENCES
- Given string S, print all nonempty
subsequences of it.
Solution
21
• PROBLEMS :
Solution
INPUT:
3
64
432211
35
211
12 400
50 50 50 50 50 50 25 25 25 25 25 25
22
• PROBLEMS :
Solution
23
!THANK YOU
MAIL : [email protected]
FACEBOOK : ICPC.MANSOURA
WEBSITE : MSC.ACM.ORG