题目:序列123...N,N介于3和9之间,在其中加入+、-或者空格,使其和为0。如123456 1-2 3-4 5+6 7 等价于1-23-45+67=0。请问,如何获得所有组合?
思路:
- 由于N是从3至9的范围,解决方案就是针对每个N的取值,先计算三个分隔符“_ + -”填入序列1-N的所有可能组合的情况总数
- 设置所有情况的组合序列(采用3进制的思想,即set函数)
- 对每种组合计算表达式值,如果为0则输出(利用栈&状态机,calculate函数)
#include <stdio.h>
/*
* Initialize the string with 1 to 9 and seperated by whitespace
* for len in range(3, 9+1):
* for each possibility of seperators:
* calculate the result, if it's zero, output
*/
int calculate(char input[], int n)
{
//Use a simple state machine to interpret the input as an expression
int stack[3] = {0}, sp = 0, i = 0;
for(; i < n*2-1; ++