题目:序列123...N,N介于3和9之间,在其中加入+、-或者空格,使其和为0,
如123456 1-2 3-4 5+6 7 等价于1-23-45+67=0。请问,如何获得所有组合?使用递归和非递归。下面的代码是别人写的,个人认为很好就收藏了。
C++代码:
//序列123...N,N介于3和9之间,在其中加入+、-或者空格,使其和为0,
//如123456 1-2 3-4 5+6 7 等价于1-23-45+67=0。请问,如何获得所有组合?使用递归和非递归。
//非递归算法
#include <iostream>
#include <cmath>
using namespace std;
void func (char* str);
void calc (char* result);
int main()
{
char str[] = "123456789";
func(str);
return 0;
}
void func(char* str)
{
//初始化输出数组
int len = strlen(str);
char* result = new char[len*2];
for (int i = 0; i < len; i++)
{
result[i*2] = str[i];
}
result[len*2-1] = '\0';
//模拟3进制的运算
char key[3] = {' ', '+', '-'};
int n = pow(3.0, len - 1);
for (int i = 0; i < n; i++)
{
//把i转换成3进制,计算每一位,转换成字符,填入字符串相应位置
int pos = len * 2 - 3; //个位数填入位置
int temp = i, mod;
do
{
mod = temp % 3;
temp /= 3;
result[pos] = key[mod];
pos -= 2;
}while (temp > 0);
//高位补0
while (pos > 0)
{
result[pos] = key[0];
pos -= 2;
}
calc(result); //计算结果并输出
}
delete[] result;
}
void calc(char* result)
{
int sum = 0, sign = 1, i = 0;
int temp = 0;
while (result[i] != '\0')
{
if (result[i] == ' ')
{
temp *= 10;
}
else if(result[i] == '+' || result[i] == '-')
{
sign = (result[i] == '+') ? 1 : -1;
sum += temp;
temp = 0;
}
else
{
temp += sign * (result[i] - '0');
}
i++;
}
sum += temp;
if (sum == 0)
{
cout << result << endl;
}
}