zoukankan      html  css  js  c++  java
  • 1370. 零和序列

    枚举每次选择的三种运算符:({' ','+','-'})(字典序),时间复杂度为(O(3^{n-1}),n le 9)

    注意点

    在数字(1)前加一个('+')方便表达式求值。

    char path[10];
    char op[]={' ','+','-'};
    int n;
    
    bool check()
    {
        int res=0;
        for(int i=1;i<=n;i++)  // 枚举当前运算数
        {
            if(path[i] == '+' or path[i] == '-')
            {
                int j=i+1;
                int t=i;
                while(j <= n && path[j] == ' ')  //双指针求出超过一位的运算数
                {
                    t = t*10 + j;
                    j++;
                }
                
                if(path[i] == '+') res += t;
                else res -= t;
                
                i=j-1;
            }
        }
        return res == 0;
    }
    
    void dfs(int u)
    {
        if(u > n)
        {
            if(check())
            {
                for(int i=1;i<=n;i++)
                {
                    if(i > 1) cout<<path[i];
                    cout<<i;
                }
                cout<<endl;
            }
            return;
        }
    
        for(int i=0;i<3;i++)
        {
            path[u]=op[i];
            dfs(u+1);
        }
    }
    
    int main()
    {
        cin>>n;
    
        path[1]='+';
        dfs(2);
        //system("pause");
        return 0;
    }
    
  • 相关阅读:
    1282 回文数猜想
    1279 验证角谷猜想
    1205 吃糖果
    1201 18岁生日
    1106 排序
    2024 C语言合法标识符
    196 让气球飞吧
    1001 Sum Problem
    if语句
    三元运算符
  • 原文地址:https://www.cnblogs.com/fxh0707/p/14852814.html
Copyright © 2011-2022 走看看