Lecture 5/1: Backtracking 2


May 1, 2020

đź“‚Associated files

More Recursive Backtracking

CS 106B: Programming Abstractions

Spring 2020, Stanford University Computer Science Department

Lecturers: Chris Gregg and Julie Zelenski

A backpack ('knapsack') that says it can hld 15kg, and a number of weights with a dollar amount and a weight. The weights are $4, 12kg; $2, 2kg; $2, 1kg; $10, 4kg, and $1, 1kg


Slide 2

Announcements


Slide 3

Today's Goals:


Slide 4

The Knapsack Problem: Find the best solution

A backpack ('knapsack') that says it can hld 15kg, and a number of weights with a dollar amount and a weight. The weights are $4, 12kg; $2, 2kg; $2, 1kg; $10, 4kg, and $1, 1kg


Slide 5

The Knapsack Problem: Find the best solution

int fillKnapsack(Vector<objectT>& objects, int targetWeight)

Slide 6

The Knapsack Problem: Solution


Slide 7

Question: Why didn't we stop at the exact moment we knew the weight was too small?


Slide 8

Boggle!

A Boggle board, with letters in a 4x4 grid. The letters in the first row of the image are 'H T D E', the second row has 'S Y R E', the third row has 'C X N A', and the fourth row has 'B U R B'


Slide 9

Back to Knapsack


Slide 10

Knapsack, find best solution, full code:

int fillKnapsack(Vector<objectT>& objects,
                 int weight, int bestScore,
                 Vector<objectT>& solutionObjects) {
  if (weight < 0) return 0; // we tried too much weight!
  int localBestScore = bestScore;
  Vector<objectT> localBestSolution = solutionObjects;
  Vector<objectT> originalSolution = solutionObjects;
  int obSize = objects.size();
  for (int i = 0; i < obSize; i++) {
      objectT originalObject = objects[i];
      int currValue = bestScore + originalObject.value;
      int currWeight = weight - originalObject.weight;

      // remove object for recursion
      objects.remove(i);

      // add it to our potential solution set
      solutionObjects.add(originalObject);

      // recurse
      currValue = fillKnapsack(objects, currWeight, currValue,
                               solutionObjects);
      if (localBestScore < currValue) {
          localBestScore = currValue;
          localBestSolution = solutionObjects;
      }

      // replace
      objects.insert(i, originalObject);

      // restore solution
      solutionObjects = originalSolution;
  }
  // we now have a best solutionsObject, and a best local score
  solutionObjects = localBestSolution;
  return localBestScore;
}

Slide 11

Finding all Knapsack Solutions??