我需要创建一个函数来接收数字和目标数字的数组,并返回可以添加或减去这些数字以获得目标数字的不同方法。
即
值= 2,4,6,8目标= 12
2 + 4 + 6 = 12,
4 + 8 = 12,
6 + 8 - 2 = 12,
2 - 4 + 6 + 8 = 12,
返回4
这是我到目前为止所做的,但它只会考虑额外的问题。
private void RecursiveSolve(int goal, int currentSum, List<int> included, List<int> notIncluded, int startIndex)
{
for (int index = startIndex; index < notIncluded.Count; index++)
{
int nextValue = notIncluded[index];
if (currentSum + nextValue == goal)
{
List<int> newResult = new List<int>(included);
newResult.Add(nextValue);
mResults.Add(newResult);
}
else if (currentSum - nextValue == goal)
{
List<int> newResult = new List<int>(included);
newResult.Add(nextValue);
mResults.Add(newResult);
}
if (currentSum - nextValue < goal && currentSum - nextValue > 0 )
{
List<int> nextIncluded = new List<int>(included);
nextIncluded.Add(nextValue);
List<int> nextNotIncluded = new List<int>(notIncluded);
nextNotIncluded.Remove(nextValue);
RecursiveSolve(goal, currentSum - nextValue, nextIncluded, nextNotIncluded, startIndex++);
}
if (currentSum + nextValue < goal)
{
List<int> nextIncluded = new List<int>(included);
nextIncluded.Add(nextValue);
List<int> nextNotIncluded = new List<int>(notIncluded);
nextNotIncluded.Remove(nextValue);
RecursiveSolve(goal, currentSum + nextValue, nextIncluded, nextNotIncluded, startIndex++);
}
}
}
答案 0 :(得分:1)
嗯,简单的方法是尝试所有的组合。如果您有N个数字,则您有3 ^ N个组合。原因是:你对数字求和,但在每个数字前加上一个系数。如果您的数字是A1..AN,则添加N个系数(C1..CN)和总和:
Sum (Ai*Ci)
您的Cis可以是1(表示您添加数字),-1(表示您减去数字)或0(表示您忽略该数字)。
因此,回顾所有3 ^ N个可能的系数分配,计算总和并与目标进行比较。
我假设所有数字都不同(如你的例子)。如果某个号码可以出现两次,则需要考虑到这一点。