Lecture 9:
Branching Recursion
CS 136: Spring 2024
Katie Keith
📣 Announcements
🎯 Today’s Learning Objectives
📚Readings
Why is recursion important in CS 136?
Looking ahead, we will use recursion throughout CS 136.
Figure credit: Wikipedia
Review: Recursive Euclid’s algorithm
public static int recursiveGcd(int p, int q){
if(q == 0){
return p;
else{
return recursiveGcd(q, p % q);
}
}
Base case: Returns a value without making any subsequent recursive calls.
Recursive step: It relates the value of the function at one (or more) input values to the value of the function at one (or more) other input values
Calling the name of the function
Modifying the inputs
public static String mystery(String s){
int strLen = s.length();
if(strLen <=1){
return s;
}
String a = s.substring(0, strLen/2);
String b = s.substring(strLen/2, strLen);
return mystery(b) + mystery(a);
}
💡Think-pair-share
Board work
TPS1.java
💻
Branching recursion
Often, we see a pattern in recursive algorithms in which each recursive call branches into one or more recursive calls, forming a tree-like structure of calls.
public static String mystery(String s){
int strLen = s.length();
if(strLen <=1){
return s;
}
String a = s.substring(0, strLen/2);
String b = s.substring(strLen/2, strLen);
return mystery(b) + mystery(a);
}
Example:
Looking ahead: Very common for problems that ask for a permutation (order matters) or combination (order does not matter) of elements
Branching recursive step:
1. Call the recursive methods multiple times (with different inputs)
2. Combine these (e.g., +, ||, &&, * etc.)
Task: Making change
Suppose we have an infinite supply of coins in different denominations.
Let’s write a program to count the number of ways to make change for an input amount using the given coin denominations.
Example
int[] coins = {1, 2, 5}; // denominations of the coins
// (but recall, we have an infinite supply of them)
int amount = 6; // amount to make change for
Number of ways to make change:
This question is asking about combinations (not permutations) since order does not matter
Tips for branching recursion problems
CoinChange.java
💻
public static int helper(int[] coins, int amount, int index) {
if (amount == 0) {return 1;}
if (amount < 0 || index == coins.length) {return 0;}
int includeCurrentCoin = helper(coins, amount - coins[index], index);
int excludeCurrentCoin = helper(coins, amount, index + 1);
return includeCurrentCoin + excludeCurrentCoin;
}
Draw the recursive call tree for this example. In the end, what does ways equal?
int[] coins = {1, 2};
int amount = 3;
int ways = helper(coins, amount, 0);
💡Think-pair-share
✅
✅
🎯 Today’s Learning Objectives