D - How Many Equations Can You Find

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.

Input

Each 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.

Output

The 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

题目大意

     将数字字符串分成一部分,选择正负号,然后相加,不过要注意,第一个子串必须是正的,(题目要求)。

思路

扫描二维码关注公众号,回复: 2537173 查看本文章

由此可以知道,每一步下接两步,加或则减,想到了二叉树和深度优先搜索。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <bits/stdc++.h>

using namespace std;

int n;
string s;
//int vis[13][13]; 是一直往后推,便不需要标记了,自然不需要回溯了
int sum;
void dfs(int x,int res)
{
    int j,k,ans;
    if(x==s.length()){
        if(res==n)sum++;
        return ;
    }
        for(j=x;j<s.length();j++){     // 从当前位置出发,所构成的子字符串
          ans=0;
          for(k=x;k<=j;k++){
            ans=ans*10+s[k]-'0';
          }
          dfs(j+1,res+ans);
          if(x!=0)dfs(j+1,res-ans);  // 第一个子串,不能为负
    }
}
int main()
{
    while(cin>>s>>n){
        sum=0;
        dfs(0,0);
        cout << sum << endl;
    }
    return 0;
}

  

猜你喜欢

转载自blog.csdn.net/hnlg311709000526/article/details/81334897
今日推荐