旧上衣codeR谜:通过将制作一个号码+ [英] Old Top Coder riddle: Making a number by inserting +

查看:161
本文介绍了旧上衣codeR谜:通过将制作一个号码+的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这顶codeR问题的。

鉴于数字串,发现增加所需的等于某些目标数字的字符串的最小数目。每次加入是某处插入一个加号进入数字串的等效。插入所有加号后,评价的总和如常。

Given a string of digits, find the minimum number of additions required for the string to equal some target number. Each addition is the equivalent of inserting a plus sign somewhere into the string of digits. After all plus signs are inserted, evaluate the sum as usual.

例如,请考虑303和6的目标和的最佳策略就是3 + 03。

For example, consider "303" and a target sum of 6. The best strategy is "3+03".

我会如下解决它与蛮力:

I would solve it with brute force as follows:


for each i in 0 to 9 // i -- number of plus signs to insert
  for each combination c of i from 10
    for each pos in c // we can just split the string w/o inserting plus signs
      insert plus sign in position pos 
    evaluate the expression
    if the expression value == given sum
      return i

是否有意义?它是从性能的角度来看最优的?

Does it make sense? Is it optimal from the performance point of view?

...

好了,现在我看到一个动态规划解决方案的效率会更高。然而有趣的是,如果presented解决方案是有道理的呢。

Well, now I see that a dynamic programming solution will be more efficient. However it is interesting if the presented solution makes sense anyway.

推荐答案

这当然不是最优的。如果,例如,您将得到字符串1234567890,目标是一个三位数字,你知道你必须将字符串分割成至少四个部分,所以你不用查0,1,或2个刀片。此外,目标限制了可容许的插入位置的范围内。这两点对短字符串小的影响,但可以使较长的巨大差异。不过,我怀疑有一个好得多的方法,闻起来有点DP的。

It's certainly not optimal. If, for example, you are given the string "1234567890" and the target is a three-digit number, you know that you have to split the string into at least four parts, so you need not check 0, 1, or 2 inserts. Also, the target limits the range of admissible insertion positions. Both points have small impact for short strings, but can make a huge difference for longer ones. However, I suspect there's a vastly better method, smells a bit of DP.

这篇关于旧上衣codeR谜:通过将制作一个号码+的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆