Slot07 08 09 Recursion
Slot07 08 09 Recursion
1
Contents
1- Introduction to recursion.
2- Describing a recursive operation.
3- Implementing a recursive method.
4- Classifying recursive functions
5- How to manage running functions?
6- Anatomy of a Recursive Call
7- Evaluating performance of recursive
methods.
8- Eliminating recursion
9- Backtracking
2
Learning Outcomes
3
1- Introduction to recursion
Examples
Person = a child of other two persons
n! = n* (n-1)! ( factorial)
4
1- Introduction to recursion…
5
1- Introduction to recursion…
6
2- Describing a recursive operation.
7
2- Describing a recursive operation…
1 1 2 3 5 8 13 21 34
Anchors: 1, n<=2
Deductive rule: F(n) = F(n-2) + F(n-1), n>2
8
2- Describing a recursive operation…
Example: Calculate n!
n! = 1.2.3.4.5.6.…(n-1).n
= (n-1)!n = n.(n-1)!
Anchors: 1, n<2
Deductive rule: n! = n.(n-1)!
9
2- Describing a recursive operation…
Return 0,n=0
Return a[n-1] + Sum (a, n-1);
10
3- Implementing a recursive method Demo 1
Pseudo-code
n! = 1, n<2
= n* (n-1)!, n>=2
2 lines
// Other test
Để dễ tiếp thu bài học, xin đừng thắc mắc “Hàm đệ quy chạy như
thế nào?”. Câu hỏi này sẽ được trả lời ở phần sau của chương. Ở
đây, chúng ta chú tâm vào cách suy nghĩ đệ quy, diễn đạt đệ quy
và viết hàm đệ quy cho quen đã nhé.
11
3- Implementing a recursive method… Demo 2
Recursive
definitions serve
two purposes:
(1) Generating
new elements
(2) Testing
whether an
element
belongs to a
set
Demo: The
Fibonacci
sequence
12
3- Implementing a recursive method… Demo 3
13
3- Implementing a recursive method… Demo 4
// Test 1.5 3 6 12 24 48
System.out.println( gp(6, 1.5, 2)); // 48
14
3- Implementing a recursive method… Demo 5
Sum(a, n) = 0, n=0;
= Sum(a, n-1) + a[n-1], n>1
// Test :
double a[] = { 1.5, 2, 4, 5, 2, 6.5 };
System.out.println( sum(a, 6)); // 21
15
3- Implementing a recursive method… Demo 6
// Test :
int b[] = { 1, 5, 9, 7, 2, 19,10 };
System.out.println( max(b, 7)); // 19
16
3- Implementing a recursive method… Demo 7
17
3- Implementing a recursive method… Demo 8
18
4- Classifying recursive function
Aspect Types
Position where a recursive call is Tail/ non-tail | Head/ non-head
put recursion
Number of recursive calls Linear/ non-linear recursion
Recursive call is easily detected Direct/ indirect recursion
19
4- Classifying recursive functions
20
4- Classifying recursive functions…
21
4- Classifying recursive functions…
receive(buffer)
Based on
while buffer is not filled up
number of if information is still incoming
functions get a character and store it in buffer;
included in else exit();
recursive call: decode(buffer);
Indirect
recursion. decode(buffer)
decode information in buffer;
Direct store(buffer);
recursion?
Recursice call is store(buffer)
put in the body transfer information from buffer to file;
receive(buffer);
of itself
22
5- How to manage running functions?
23
5- How to manage running functions?...
24
A demo.
5- How to manage running functions?...
Parameters and Local
variables ( n ) Activation
Dynamic link (4000) record of
Return Address ( = )
= 5000 Return value ( int )
f3(…)
AR of
factorial(1)
AR of AR of AR of
factorial(2) factorial(2) factorial(2)
AR of AR of AR of AR of AR of
factorial(3) factorial(3) factorial(3) factorial(3) factorial(3)
26
7- Evaluating performance of recursive methods.
AR of
factorial(1)
AR of AR of AR of
factorial(2) factorial(2) factorial(2)
AR of AR of AR of AR of AR of
factorial(3) factorial(3) factorial(3) factorial(3) factorial(3)
27
7- Evaluating performance of recursive methods…
double fact1(int n) {
if (n<2) return 1; fact1(100); // 100 activation records
return n*fact1(n-1);
}
double fact2 (int n) {
double result =1; fact2(100); // 1 activation record
for (int i=2; i<=n; i++)
result *= i;
return result;
}
28
7- Evaluating performance of recursive methods…
One operation
must be
performed
many times.
29
7- Evaluating performance of recursive methods…
30
Recursive Call: High
memory cost + High
8- Eliminating tail recursion time cost
Recursive version
Loop version, no additive memory is needed.
31
Demo 9:
8- Eliminating tail recursion…
Convert an integer to
string numbers.
32
8- Eliminating tail recursion…
33
9- Backtracking – Hồi quy
35
9- Backtracking…
Definitions:
Problem: a set of variables (V), each variable has a distinct domain (D, set of
domains).
Problem’s Constraints: Conditions (C) on values of variables.
A solution: set of specific values of variables (configuration) which satisfy the
problem’s constraints.
Example 1: Vừa gà vừa chó bó đủ trăm chân. Hỏi có bao nhiêu gà bao nhiêu chó:
V: 2 variables, 2 domains:
sốGà: [1, (100-4)/2] , ít nhất có 1 con chó
sốChó: [ 1, (100-2)/4], ít nhất có 1 con gà
C: sốGà * 2 + sốChó *4 =100.
36
9- Backtracking…
37
9- Backtracking…
Example 4:
A customer likes to buy 3 TVs, 2 refrigerators, 1 fan with budget less than or
equals 30,000,000$ (budget)
V: 6 variables, 3 domains.
v0: { TVs }, v1: { TVs }, v2: { TVs }
v3: { Refs }, v4: { Refs }, v5: { Fans }
C: v0.price + v1.price + v2.price +
v3.price + v4.price + v5.price <= budget
Backtracking implementations:
(1) Using recursive approach
(2) Using loop approach. A generator which will generate values
(CONFIGURATION) for checking constraints.
38
9- Backtracking…
(64.63.62.61.60,59.58.57)
40
Demo 10: The Eight-
9- Backtracking… Queen Problem
41
Demo 10: The Eight-
9- Backtracking… Queen Problem
Q0 Q1 Q2 Q… Qindex
42
Demo 10: The Eight-
9- Backtracking… Queen Problem
43
Demo 10: The Eight-
9- Backtracking… Queen Problem
44
Backtracking Impl.:
Generator Approach
9- Backtracking… Generator in the Product
consulting Problem
tvDom tvDom tvDom rfDom rfDom fanDom
0 TV1 TV1 TV1 RF1 RF1 F1
1 TV2 TV2 TV2 RF2 RF2 F2
2 TV3 TV3 TV3 RF3 RF3 F3
3 TV4 TV4 TV4 Get a
RF4 RF4 suggestion
4 TV5 TV5 TV5 RF5 RF5
5 TV6 TV6 TV6
45
9- Backtracking… Demo 10: The Eight-
Queen Problem
Backtracking: Complexity
• N: average quantity of each domain. There are n options which can
be used to assign a value to each variable
• |V|: number of variables ( a configuration has V values)
Product principal Complexity of backtracking algorithm: N|V|
Hard problem
47
9- Backtracking… Demo 11,12,13,14
Backtracking
generator
Demo 14
Demo 11
Demo 12
Demo 13
48
9- Backtracking…
49
9- Backtracking…
50
9- Backtracking…
51
9- Backtracking…
52
9- Backtracking…
53
9- Backtracking…
54
9- Backtracking…
One-step backtracking
55
9- Backtracking…
Using Backtrack
generator in some
specific problems
56
9- Backtracking…
Using Backtracking
Generator
57
9- Backtracking…
58
9- Backtracking…
59
9- Backtracking…
60
9- Backtracking…
61
9- Backtracking…
62
9- Backtracking…
63
9- Backtracking…
64
9- Backtracking…
65
9- Backtracking…
66
9- Backtracking…
Situation:
A customer likes to
buy 3 TVs, 2
refrigerators, 1 fan
with maximum budget
of 30,000,000$
67
9- Backtracking…
Using Backtracking Generator
68
9- Backtracking…
69
9- Backtracking…
70
9- Backtracking…
71
9- Backtracking…
72
9- Backtracking…
73
9- Backtracking…
74
9- Backtracking…
75
9- Backtracking…
76
9- Backtracking…
Using
Backtracking
Generator
77
9- Backtracking…
78
Recursion Review
LO3.1thatDescribe the basic ideas of recursion and how to set up recursive systems
represent certain real-world phenomena.
LO3.4 Analyse a recursive function to find out its’ ouput without running.
LO3.5 Explain type of recursive functions, give examples and comparing them.
LO3.6 Compare recursion with iteration, analyzes their pros and cons
79
Recursion Review
Ôn tập – Viết vào vở
1- Đệ quy là gì?
2- Con người có dùng kỹ thuật đệ quy hay không? Cho hai thí dụ.
3- Làm sao con người hiểu được đệ quy?
4- Tác vụ đệ quy được mô tả như thế nào? Cho thí dụ.
5- Làm sao có được kỹ năng diễn đạt đệ quy?
6- Đệ quy được dùng để làm gì?
7- Đệ quy đuôi là gì?
8- Đệ quy đầu là gì?
9- Đệ quy tuyến tính là gì?
10- Đệ quy phi tuyến là gì?
11- Đệ quy gián tiếp là gì?
12- Đệ quy hỗ tương là gì?
13- Làm sao hệ thống có thể quản lý các hàm đang thực thi?
14- Hãy cho biết activation record của một hàm gồm có những gì cùng với ý nghĩa của từng thành phần.
15- Tại sao hàm đệ quy khi thực thi lại tốn bộ nhớ?
16- Tại sao hàm đệ quy thực thi lại chậm?
17- Khử đệ quy là gì? Tại sao lại nên khử đệ quy?
18- Khử đệ quy bằng cách nào?
19- Hồi quy là gì?
20- Kỹ thuật hồi quy có thể được dùng trong những bài toán nào? Cho ví dụ.
80
Q&A
81
82