YunYan

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
Now give you an string which only contains 0, 1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9.You are asked to add the sign ‘+’ or ’-’ between the characters. Just like give you a string “12345”, you can work out a string “123+4-5”. Now give you an integer N, please tell me how many ways can you find to make the result of the string equal to N .You can only choose at most one sign between two adjacent characters.

InputEach case contains a string s and a number N . You may be sure the length of the string will not exceed 12 and the absolute value of N will not exceed 999999999999.OutputThe output contains one line for each data set : the number of ways you can find to make the equation.Sample Input

123456789 3
21 1

Sample Output

18
1

题目大意就是 在一个在来两个数字之间添加+ — 或者不做处理 使他可以得到后一个数,并记录次数就好了
思路:DFS遍历每一种情况
#include<iostream>
#include<string >
using namespace std;
string a;
typedef long long ll;
ll n,ans;
void dfs(int row,int sum){
    if(row==a.size())
    {
        if(sum==n)
            ans++;
        return ;
    }
    
    ll t=0;
    for(int i=row;i<a.size();i++)
    {
        t=t*10+a[i]-'0';
        dfs(i+1,sum+t);
        if(row==0) continue ;  //因为当row==0时 sum=0,如过加减号的话相当于在第一个数前边加负号,所以要跳过
     dfs(i+1,sum-t); } } int main() { while(cin>>a>>n){ ans=0; dfs(0,0); cout<<ans<<endl; } return 0; }

 

posted on 2019-07-25 09:07  Target--fly  阅读(156)  评论(0编辑  收藏  举报