2023 Slot06 Recursion Python
2023 Slot06 Recursion Python
Slot 06 – Recursion
Advisor:
Dr. Nguyễn Tiến Huy
Dr. Lê Thanh Tùng
1 Introduction
2 Recursion Function
3 Examples
4 Dynamic Programming
RecursiveFunction(){
if (test for simple case){
Compute the solution without recursion
}
else{
Break the problem into subproblems of the same form
Call RecursiveFunction() on each subproblem
Reassamble the results of the subproblems
}
}
▪ The structure of recursive functions is typically like the following
Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 12
Recursion Function
▪ 3 “must have” of a recursive algorithm
▪ Your code must have a case for all valid inputs
▪ You must have a base case with no recursive calls.
▪ When you make a recursive case, it should be to a simpler instance
and make forward progress towards the base case
▪ Recursion definition:
▪ Base case:
# If the weight of the nth item is more than the knapsack capacity,
# the item cannot be included in the optimal solution
if weights[n-1] > capacity:
return knapsack_recursive(capacity, weights, values, n-1)
items_selected.reverse()
return dp[n][capacity], items_selected