Write a function that given a string of digits and a target value, prints where to put +'s and *'s between the digits so they combine exactly to the target value. Note there may be more than one answer, it doesn't matter which one you print.
Examples:
"1231231234",11353 -> "12*3+1+23*123*4"
"3456237490",1185 -> "3*4*56+2+3*7+490"
"3456237490",9191 -> "no solution"
方案一:(不是俺想出)可供参考(用了穷举法)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Code
static void Main(string[] args)
{
Check("22", 1/*Should start from 1*/, 4);
Check("3456237490", 1/*Should start from 1*/, 1185);
Check("3456237490", 1/*Should start from 1*/, 9191);
}
public static void Check(string str,int index, int expectedResult)
{
string testStr = string.Empty;
for (int i = index; i < str.Length; i++)
{
//Check index +
testStr = str.Insert(i, "+");
if (Evaluate(testStr) == expectedResult)
Console.WriteLine(testStr + "=" + expectedResult);
Check(testStr, i + 2, expectedResult);
//Check index *
testStr = str.Insert(i, "*");
if (Evaluate(testStr) == expectedResult)
Console.WriteLine(testStr + "=" + expectedResult);
Check(testStr, i + 2, expectedResult);
}
}
public static long Evaluate(string expression)
{
List<string> strs = new List<string>();
string str = string.Empty;
foreach (char ch in expression.ToCharArray())
{
switch (ch)
{
case '*':
if (str != string.Empty)
strs.Add(str);
str = string.Empty;
strs.Add("*");
break;
case '+':
if (str != string.Empty)
strs.Add(str);
str = string.Empty;
strs.Add("+");
break;
default:
str += ch.ToString();
break;
}
}
if (str != string.Empty)
strs.Add(str);
Stack<long> intStack = new Stack<long>();
for (int i = 0; i < strs.Count; i++ )
{
switch (strs[i])
{
case "+":
break;
case "*":
long before = intStack.Pop();
long next = long.Parse(strs[++i]);
intStack.Push(before * next);
break;
default:
intStack.Push(long.Parse(strs[i]));
break;
}
}
long result = 0;
while (intStack.Count > 0)
result += intStack.Pop();
return result;
}
}