以下是一个递归函数,将打印所有有效的组合和无效的组合。
代码(在此测试:这里,或简化版本 这里):
using System;
namespace algorithm_simple_csharp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Working on it!");
int[] allNumbers = new int[] {1,2,3,4};
int desiredSum = 0;
int initIndex = 0;
OperationTreeNode firstPositiveNode = new OperationTreeNode
{
parentNode = null,
currentNumber = allNumbers[initIndex],
accumulativeSum = allNumbers[initIndex],
operation = "+"
};
int totalSolutionsPositiveFirst = ApplyNumber(firstPositiveNode, allNumbers, initIndex + 1, desiredSum);
OperationTreeNode firstNegativeNode = new OperationTreeNode
{
parentNode = null,
currentNumber = -allNumbers[initIndex],
accumulativeSum = -allNumbers[initIndex],
operation = "-"
};
int totalSolutionsNegativeFirst = ApplyNumber(firstNegativeNode, allNumbers, initIndex + 1, desiredSum);
Console.WriteLine("Total soltions: " + (totalSolutionsPositiveFirst + totalSolutionsNegativeFirst));
}
static int ApplyNumber(OperationTreeNode currentNode, int[] allNumbers, int index, int desiredSum)
{
if(index > allNumbers.GetUpperBound(0))
{
if(currentNode.accumulativeSum == desiredSum)
{
Console.WriteLine(currentNode.BranchToString() + " = " + currentNode.accumulativeSum + " <--- THIS ONE");
return 1;
}
Console.WriteLine(currentNode.BranchToString() + " = " + currentNode.accumulativeSum);
return 0;
}
OperationTreeNode plusNode = new OperationTreeNode
{
parentNode = currentNode,
currentNumber = allNumbers[index],
accumulativeSum = currentNode.accumulativeSum + allNumbers[index],
operation = "+"
};
int totalSolutionsWithPlus = ApplyNumber(plusNode, allNumbers, index +1, desiredSum);
OperationTreeNode minusNode = new OperationTreeNode
{
parentNode = currentNode,
currentNumber = allNumbers[index],
accumulativeSum = currentNode.accumulativeSum - allNumbers[index],
operation = "-"
};
int totalSolutionsWithMinus = ApplyNumber(minusNode, allNumbers, index +1, desiredSum);
return totalSolutionsWithPlus + totalSolutionsWithMinus;
}
}
public class OperationTreeNode
{
public int accumulativeSum = 0;
public OperationTreeNode parentNode = null;
public int currentNumber = 0;
public string operation;
public string BranchToString()
{
if(parentNode == null)
{
return $"{this.currentNumber} ";
}
return $"{parentNode.BranchToString()} {this.operation} {this.currentNumber} ";
}
}
}
控制台输出
Working on it!
1 + 2 + 3 + 4 = 10
1 + 2 + 3 - 4 = 2
1 + 2 - 3 + 4 = 4
1 + 2 - 3 - 4 = -4
1 - 2 + 3 + 4 = 6
1 - 2 + 3 - 4 = -2
1 - 2 - 3 + 4 = 0 <--- THIS ONE
1 - 2 - 3 - 4 = -8
-1 + 2 + 3 + 4 = 8
-1 + 2 + 3 - 4 = 0 <--- THIS ONE
-1 + 2 - 3 + 4 = 2
-1 + 2 - 3 - 4 = -6
-1 - 2 + 3 + 4 = 4
-1 - 2 + 3 - 4 = -4
-1 - 2 - 3 + 4 = -2
-1 - 2 - 3 - 4 = -10
Total soltions: 2
它是如何工作的?
它创建一棵树。每个树节点都是类型为OperationTreeNode
的对象,表示数字及其操作。例如:+1和-1是两个OperationTreeNode
。
当您到达最后一个数字时,ApplyNumber
将评估该节点是否等于desiredSum
。
ApplyNumber
返回子树找到多少解决方案。
+1 -1 +2 -2 +3 -3 +4 -4
可以是一种解决方案,而+5 -5 +6 -6 +7 -7 +8 -8
却不在你的可能解决方案列表中,这也不是很清楚。 - Luuk