zoukankan      html  css  js  c++  java
  • B

    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; }
  • 相关阅读:
    mybatis 入门基础
    spring学习总结
    综合练习:词频统计
    组合数据类型综合练习
    Python基础综合练习
    熟悉常用的Linux操作
    1.大数据概述
    C程序语法(无左递归)
    文法规则
    实验一词法分析报告
  • 原文地址:https://www.cnblogs.com/Accepting/p/11242112.html
Copyright © 2011-2022 走看看