zoukankan      html  css  js  c++  java
  • 282. Expression Add Operators

    Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +-, or * between the digits so they evaluate to the target value.

    Example 1:

    Input: num = "123", target = 6
    Output: ["1+2+3", "1*2*3"] 
    

    Example 2:

    Input: num = "232", target = 8
    Output: ["2*3+2", "2+3*2"]

    Example 3:

    Input: num = "105", target = 5 Output: ["1*0+5","10-5"]

    Example 4:

    Input: num = "00", target = 0
    Output: ["0+0", "0-0", "0*0"]
    

    Example 5:

    Input: num = "3456237490", target = 9191
    Output: []

    Approach #1: DFS. [C++]

    class Solution {
    public:
        vector<string> addOperators(string num, int target) {
            vector<string> ans;
            dfs(num, target, 0, "", 0, 0, &ans);
            return ans;
        }
        
    private:
        void dfs(const string& num, const int target,
                 int pos, const string& exp, long prev, long curr,
                 vector<string>* ans) {
            if (pos == num.length()) {
                if (curr == target) ans->push_back(exp);
                return;
            }
            
            for (int l = 1; l <= num.length()-pos; ++l) {
                string t = num.substr(pos, l);
                if (t[0] == '0' && t.length() > 1) break;
                long n = std::stol(t);
                if (n > INT_MAX) break;
                if (pos == 0) {
                    dfs(num, target, l, t, n, n, ans);
                    continue;
                }
                dfs(num, target, pos + l, exp + '+' + t, n, curr + n, ans);
                dfs(num, target, pos + l, exp + '-' + t, -n, curr - n, ans);
                dfs(num, target, pos + l, exp + '*' + t, prev * n, curr - prev + prev * n, ans);
            }
        }
    };
    

      

    Analysis:

    http://zxi.mytechroad.com/blog/searching/leetcode-282-expression-add-operators/

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    什么是webApp?与原生APP的区别
    判断h5是否在小程序内打开
    移动端 1px边框
    【填坑】小程序webview使用简单汇总
    一个小程序账号只能发布一个小程序
    微信开发工具提示未绑定网页开发者
    小程序webview(业务域名配置)
    webpack打包已开发好的vue项目
    vscode搭建本地服务器
    微信扫码下载,H5引导页
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10331331.html
Copyright © 2011-2022 走看看