http://blog.csdn.net/redooder/article/details/11714509
问题描述:给出1-9数字,再给出一个和数n ;1_2_3_4_5_6_7_8_9 = n; 两个数字中间的符号可以“+”或者“-”或者是空,空的话就表示两个数连起来,例如123+45-6+7+89 = n;给出一个数N,求所有可能解。
#include <stdio.h>
int lu(int input){
// 0:12 1:1+2 2:1-2
int a[8] = {0};
int counter = 0;
for(a[0] = 0;a[0]<3;a[0]++){
for(a[1] = 0;a[1]<3;a[1]++){
for( a[2] = 0;a[2]<3;a[2]++){
for(a[3] = 0;a[3]<3;a[3]++){
for( a[4] = 0;a[4]<3;a[4]++){
for(a[5] = 0;a[5]<3;a[5]++){
for( a[6] = 0;a[6]<3;a[6]++){
for(a[7] = 0;a[7]<3;a[7]++){
int A[9] = {1,2,3,4,5,6,7,8,9};
int total = 0;
for (int i = 0; i<8; ) {
if (a[i] == 0) {
int t = i;
while (a[i]==0) {
A[t]*=10;
A[t]+=A[i+1];
A[i+1] = 0;
i++;
}
}else i++;
}
for (int i = 0; i<9; i++) {
if (A[i]!=0&&i!=0&&a[i-1]==1) {
total += A[i];
}
if (A[i]!=0&&i!=0&&a[i-1]==2) {
total -= A[i];
}
if (A[i]!=0&&i==0) {
total += A[i];
}
}
if(total == input){
counter++;
/*
for (int i = 0; i<9; i++) {
if(A[i]!=0){
if (i!=0&&a[i-1]==1) {
printf("+");
}
if (i!=0&&a[i-1]==2) {
printf("-");
}
printf("%d",A[i]);
}
}
printf(" = %d\n",total);
*/
}
}
}
}
}
}
}
}
}
return counter;
};
int main(int argc, const char * argv[])
{
printf("input a number:\n");
int n;
scanf("%d",&n);
printf("total: %d\n",lu(n));
return 0;
}