Section 4. Recursive Backtracking


Section materials curated by Nick Bowman and Kylie Jue, drawing upon materials from previous quarters.

This week’s section exercises continue our exploration of recursion to tackle even more challenging and interesting problems. In particular, many of this week's section problems center around recursive backtracking, a very powerful and versatile problem solving technique.

Remember that every week we will also be releasing a Qt Creator project containing starter code and testing infrastructure for that week's section problems. When a problem name is followed by the name of a .cpp file, that means you can practice writing the code for that problem in the named file of the Qt Creator project. Here is the zip of the section starter code:

📦 Starter code

1) Win some, lose sum (sum.cpp)

Topics: recursive backtracking

Write a recursive function named canMakeSum that takes a reference to a Vector<int> and an int target value and returns true if it is possible to have some selection of values from the Vector that sum to the target value. In particular, you should be implementing a function with the following declaration

bool canMakeSum(Vector<int>& values, int target)

For example, let's say that we executed the following code

Vector<int> nums = {1,1,2,3,5};
canMakeSum(nums, 9)

We should expect that the call to canMakeSum should return true. Given the values specified in nums, we can select 1, 3, and 5 such that 5 + 3 + 1 = 9.

However, let's say that we executed the following code instead

Vector<int> nums = {1,4,5,6};
canMakeSum(nums, 8);

We should expect that the call to canMakeSum in this case should return false, since there is no possible combination of values from the vector that sum up to the target value of 8.

bool canMakeSumHelper(Vector<int>& v, int target, int cur, int index) {
	if (index >= v.size()) {
		return cur == target;
	}
	return canMakeSumHelper(v, target, cur + v[index], index + 1) ||
		   canMakeSumHelper(v, target, cur, index + 1);
}

bool canMakeSum(Vector<int>& v, int target) {
	return canMakeSumHelper(v, target, 0, 0);
}

2) Change We Can Believe In (change.cpp)

Topic: Recursive Backtracking

In the US, as is the case in most countries, the best way to give change for any total is to use a greedy strategy – find the highest-denomination coin that’s less than the total amount, give one of those coins, and repeat. For example, to pay someone 97¢ in the US in cash, the best strategy would be to

  • give a half dollar (50¢ given, 47¢ remain), then
  • give a quarter (75¢ given, 22¢ remain), then
  • give a dime (85¢ given, 12¢ remain), then
  • give a dime (95¢ given, 2¢ remain), then
  • give a penny (96¢ given, 1¢ remain), then
  • give another penny (97¢ given, 0¢ remain).

This uses six total coins, and there’s no way to use fewer coins to achieve the same total.

However, it’s possible to come up with coin systems where this greedy strategy doesn’t always use the fewest number of coins. For example, in the tiny country of Recursia, the residents have decided to use the denominations 1¢, 12¢, 14¢, and 63¢, for some strange reason. So suppose you need to give back 24¢ in change. The best way to do this would be to give back two 12¢ coins. However, with the greedy strategy of always picking the highest-denomination coin that’s less than the total, you’d pick a 14¢ coin and ten 1¢ coins for a total of eleven coins. That’s pretty bad!

Your task is to write a function

int fewestCoinsFor(int cents, Set<int>& coins)

that takes as input a number of cents and a Set indicating the different denominations of coins used in a country, then returns the minimum number of coins required to make change for that total. In the case of US coins, this should always return the same number as the greedy approach, but in general it might return a lot fewer!

You can assume that the set of coins always contains a 1¢ coin, so you never need to worry about the case where it’s simply not possible to make change for some total. You can also assume that there are no coins worth exactly 0¢ or a negative number of cents. Finally, you can assume that the number of cents to make change for is nonnegative.

Makes cents? I certainly hope so.

The idea behind this solution is the following: if we need to make change for zero cents, the only (and, therefore, best!) option is to use 0 coins. Otherwise, we need to give back at least one coin. What’s the first coin we should hand back? We don’t know which one it is, but we can say that it’s got to be one of the coins from our options and that that coin can’t be worth more than the total. So we’ll try each of those options in turn, see which one ends up requiring the fewest coins for the remainder, then go with that choice. The code for this is really elegant and is shown here:

/**
 * Given a collection of denominations and an amount to give in change, returns
 * the minimum number of coins required to make change for it.
 *
 * @param cents How many cents we need to give back.
 * @param coins The set of coins we can use.
 * @return The minimum number of coins needed to make change.
 */
int fewestCoinsFor(int cents, Set<int>& coins) {
	/* Base case: You need no coins to give change for no cents. */
	if (cents == 0) {
		return 0;
	}
	/* Recursive case: try each possible coin that doesn’t exceed the total as
	* as our first coin.
	*/
	else {
		int bestSoFar = cents + 1; // Can never need this many coins;
		for (int coin: coins) {
			/* If this coin doesn’t exceed the total, try using it. */
			if (coin <= cents) {
				bestSoFar = min(bestSoFar, 
					fewestCoinsFor(cents - coin, coins));
			}
		}
		return bestSoFar + 1; // For the coin we just used.
 	}
}

3) Longest Common Subsequence (lcs.cpp)

Topic: Recursive Backtracking

Write a recursive function named longestCommonSubsequence that returns the longest common subsequence of two strings passed as arguments. Some example function calls and return values are shown below.

Recall that if a string is a subsequence of another, each of its letters occurs in the longer string in the same order, but not necessarily consecutively.

Hint: In the recursive case, compare the first character of each string. What one recursive call can you make if they are the same? What two recursive calls do you try if they are different?

longestCommonSubsequence("cs106a", "cs106b") --> "cs106" 
longestCommonSubsequence("nick", "julie") --> "i" 
longestCommonSubsequence("karel", "c++") --> "" 
longestCommonSubsequence("she sells", "seashells") --> "sesells"
string longestCommonSubsequence(string s1, string s2) {
	if (s1.length() == 0 || s2.length() == 0) {
		return "";
 	} else if (s1[0] == s2[0]) {
 		return s1[0] + longestCommonSubsequence(s1.substr(1), 
 							s2.substr(1));
 	} else {
 		string choice1 = longestCommonSubsequence(s1, s2.substr(1));
		string choice2 = longestCommonSubsequence(s1.substr(1), s2);
		if (choice1.length() >= choice2.length()) {
			return choice1;
		} else {
			return choice2;
		}
	}
}

4) Cracking Passwords(crack.cpp)

Topic: Recursive Backtracking

Write a function crack that takes in the maximum length a site allows for a user's password and tries to find the password into an account by using recursive backtracking to attempt all possible passwords up to that length (inclusive). Assume you have access to the function bool login(string password) that returns true if a password is correct. You can also assume that the passwords are entirely alphabetic and case-sensitive. You should return the correct password you find, or the empty string if you cannot find the password. You should return the empty string if the maximum length passed is 0 and raise an error if the length is negative.

Security note: The ease with which computers can brute-force passwords is the reason why login systems usually permit only a certain number of login attempts at a time before timing out. It’s also why long passwords that contain a variety of different characters are better! Try experimenting with how long it takes to crack longer and more complex passwords. See the comic here for more information: https://xkcd.com/936/

string crackHelper(string soFar, int maxLength) {
	if (login(soFar)) {
		return soFar;
	}
	if (soFar.size() == maxLength) {
		return "";
	}
	for (char c = 'a'; c <= 'z'; c++) {
		string password = crackHelper (soFar + c, maxLength);
		if (password != "") {
			return password;
		}
 		// Also check uppercase
 		char upperC = toupper(c);
 		password = crackHelper (soFar + upperC, maxLength);
		if (password != "") {
 			return password;
 		}
 	}
	return "";
}

string crack(int maxLength) {
	if (maxLength < 0) {
 		error("max length cannot be negative!);";
	}
 	return crackHelper("", maxLength);
}

5) The Knapsack Problem (knapsack.cpp)

As a challenge problem, we encourage you to explore solving the quintessential optimization challenge of the knapsack problem. As a reminder from lecture, here is the problem setup.

Imagine yourself in a new lifestyle as a professional wilderness survival expert. You are about to set off on a challenging expedition, and you need to pack your knapsack (or backpack) full of supplies. You have a list full of supplies (each of which has a survival value and a weight associated with it) to choose from. Your backpack is only sturdy enough to hold a certain amount of weight. The question is: How can you maximize the survival value of your backpack?

Assume each item in your backpack is modeled with the following struct:

struct BackpackItem {
    int survivalValue;  // You can assume this value will always >= 0
    int weight;         // You can assume this value will always >= 0
};

Your goal is to implement the following function:

int fillBackpack(Vector<BackpackItem>& items, int targetWeight);

which given a list of all possible items that you can take with you and the maximum weight that your backpack can hold, returns the maximum survival value that you can achieve by filling the backpack.

int fillBackpackHelper(Vector<BackpackItem>& items, int capacityRemaining, int curValue, int index) {
    /* Base Case: If there is no more capacity in the backpack to hold things,
     * then we can no longer fit any more value in.
     */
    if (capacityRemaining < 0) {
        return 0;
    }
    /* Base Case: If we have run out of items to consider, then the best value we
     * can get is what we've built up so far.
     */
    else if (index == items.size()) {
        return curValue;
    }else {
        /* Choose: Select an item to decide whether to bring along or not.
         */
        BackpackItem curItem = items[index];

        /* Explore: Try including the item and not including it, and keep track
         * of the best possible value in each case. */
        int bestValueWithout = fillBackpackHelper(items,
                                                  capacityRemaining,
                                                  curValue,
                                                  index + 1);

        int bestValueWith = fillBackpackHelper(items,
                                               capacityRemaining - curItem.weight,
                                               curValue + curItem.survivalValue,
                                               index + 1);

        /* Unchoose: No explicit unchoose necessary since no changes to data
         * structures have been made.
         */

        /* The final value we return is the best of the two options we tried. */
        return max(bestValueWith, bestValueWithout);
    }
}

int fillBackpack(Vector<BackpackItem>& items, int targetWeight) {
    return fillBackpackHelper(items, targetWeight, 0, 0);
}