CS106B-Section Handout #3(7)

这个题没弄太明白想到的思路,所以MARK下

Problem 7: Old-Fashioned Measuring
In Dickens’s time, merchants measured many commodities using weights and a two-pan balance—a practice that continues in many parts of the world today. If you are using a limited set of weights, however, you can only easure certain quantities accurately.
For example, suppose that you have only two weights: a 1-ounce weight and a 3-ounce weight.  With these you can easily measure out 4 ounces
It is somewhat more interesting to discover that you can also measure out 2 ounces by shifting the 1-ounce weight to the other side
Write a recursive function

bool IsMeasurable(int target, Vector<int> & weights)

that determines whether it is possible to measure out the desired target amount with a given set of weights. The available weights are stored in the int vector weights. For instance, the sample set of two weights illustrated above could be represented using the following code:

Vector<int> sampleWeights;

sampleWeights.add(1);

sampleWeights.add(3);

Given this vector, the function call

IsMeasurable(2, sampleWeights)

should return true because it is possible to measure out 2 ounces using the sample weight set as illustrated in the preceding diagram. On the other hand, calling

IsMeasurable(5, sampleWeights)

should return false because it is impossible to use the 1- and 3-ounce weights to add up to 5 ounces.
The fundamental observation you need to make for this problem is that each weight in the vector can be either:
1. Put on the opposite side of the balance from the sample
2. Put on the same side of the balance as the sample
3. Left off the balance entirely
If you consider one of the weights in the vector and determine how choosing one of these three options affects the rest of the problem, you should be able to come up with the recursive insight you need to solve the problem.


answer:

bool RecIsMeasurable(int target, Vector<int> & weights, int index)
{
  if (target == 0)
  {
    return true;
  }
  if (index >= weights.size())
  {
    return false;
  }
  return (RecIsMeasurable(target + weights[index], weights, index + 1)
 || RecIsMeasurable(target, weights, index + 1)
 || RecIsMeasurable(target - weights[index], weights, index + 1));
}
 
bool IsMeasurable(int target, Vector<int> & weights)
{ 
  return RecIsMeasurable(target, weights, 0);
 
}

你可能感兴趣的:(CS106B-Section Handout #3(7))