http://acm.hdu.edu.cn/showproblem.php?pid=2266
题解 : 两个dfs同时搜 因为是可以又加又减的 注意回溯
#include<cstdio>
#include<cstring>
#include<string.h>
#include<algorithm>
#include<iostream>
#include<stdlib.h>
using namespace std;
const int inf=0x3f3f3f3f;
const int maxn=1000000;
char s[41];
int n;
int ans,l;
void dfs(int k,int sum){
if(k==l){
if(sum==n)
ans++;
return ;
}
long long ans=0;
for(int i=k;i<l;i++){
ans=ans*10+s[i]-'0';//巧妙的操作
//两个dfs同时搜 (- +)
dfs(i+1,sum+ans);
if(k!=0){//不能初始减去第一个数
dfs(i+1,sum-ans);
}
}
}
int main(){
while(~scanf("%s",s)){
cin>>n;
l=strlen(s);
ans=0;
dfs(0,0);//数组下标 和
cout<<ans<<endl;
}
}