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);
 
}

转载于:https://my.oschina.net/u/1763504/blog/299685

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值