日期:2014-05-19  浏览次数:20853 次

正进行一个网上笔试题,感觉挺难的,请高手指点!研究中,在线等。。。
We   have   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.   For   example,   consider   the   string   "12 ".   With   zero   additions,   we   can   achieve   the   number   12.   If   we   insert   one   plus   sign   into   the   string,   we   get   "1+2 ",   which   evaluates   to   3.   So,   in   that   case,   given   "12 ",   a   minimum   of   1   addition   is   required   to   get   the   number   3.   As   another   example,   consider   "303 "   and   a   target   sum   of   6.   The   best   strategy   is   not   "3+0+3 ",   but   "3+03 ".   You   can   do   this   because   leading   zeros   do   not   change   the   result.  

Write   a   class   SimpleSums   that   contains   the   method   minMSums,   which   takes   a   String   numbers   and   an   int   sum.   The   method   should   calculate   and   return   the   minimum   number   of   additions   required   to   create   an   expression   from   numbers   that   evaluates   to   sum.   If   this   is   impossible,   return   -1.


Definition  
Class:   SimpleSums  
Method:   minSums  
Parameters:   String,   int  
Returns:   int  
Method   signature:   int   minSums(String   numbers,   int   sum)  
(be   sure   your   method   is   public)  
 

Constraints  
-   numbers   will   contain   between   1   and   10   characters,   inclusive.  
-   Each   character   in   numbers   will   be   a   digit.  
-   sum   will   be   between   0   and   100,   inclusive.  


上面是题目,用程序实现。

------解决方案--------------------
Microsoft Net Meeting?
看来你的下次了~~继续加油吧...

这道题大家都能想到的办法就是列出所有加号情况,
要费点脑子的话,可以用贪婪+回溯解决.

下面用二进制法产生加号全排列,解决此问题,不保证完全正确,参考.
public static int MinSum(string numbers, int sum)
{
string number2 = numbers.Replace( "0 ", " ");
int len2 = number2.Length; //非零数字个数
int len = numbers.Length;
if (sum < len2) //如果和小于非零数字个数,则无法组合
{
return -1;
}
else if (sum == len2) //如果相等,和等于所有非零数字相加,返回非零数字个数
{
return len2;
}
else if (sum > len2)
{
int currentSum = 0; //当前和