实验要求:
问题:
1、2、3……9利用+、-、‘空格’去组合,能否得出一个等于100的等式呢?求出他们吧。
举例:
123+4-5+67-89=100
输出:
学习内容:
(可利用回溯法)
这里利用排列组合暴力解决
代码:
下面展示一些 内联代码片
。
// A code block
var foo = 'bar';
//c++代码
#include<iostream>
using namespace std;
int jjj=0;
int func(char *b){ //计算当前组合是否能得出100
int res=0;
int temp=0; //空格是计算连续的大小
for(int i=0;i<9;i++){ //计算当前字符排列的值
if(i==0&&b[i]==' '){
temp=i+1;
while(b[i+1]==' '&&i<9){
temp=temp*10+(i+2);
i++;
}
res+=temp;
temp=0;
}
else{
if(b[i]=='-'){
temp=i+1;
while(b[i+1]==' '&&i<9){
temp=temp*10+(i+2);
i++;
}
res-=temp;
temp=0;
}
else{ //+
temp=i+1;
while(b[i+1]==' '&&i<9){
temp=temp*10+(i+2);
i++;
}
res+=temp;
temp=0;
}
}
}
return res;
}
void pprint(char *b){
for(int i=0;i<9;i++){
if(b[i]==' '){
cout<<i+1;
}
else{
cout<<b[i]<<i+1;
}
}
cout<<endl;
}
void print(int x,char *b){ //倒数第几个符号已经确定 b为字符集
char d[9];
char e[9];
for(int i=0;i<9;i++){
d[i]=b[i];
e[i]=b[i];
}
if(x>=0){
d[x]='-';
if(func(d)==100)
{
pprint(d);
}
e[x]=' ';
if(x!=0&&func(e)==100) //这里
{
pprint(e);
}
print(x-1,b);
print(x-1,d);
print(x-1,e);
}
}
int main(){
char b[9]={' ','+','+','+','+','+','+','+','+'}; //9^3
print(8,b);
if(func(b)==100)
{
pprint(b);
}
}