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: []
    

    解题思路:

    这道题可以想到使用dfs来做,但是在dfs的过程中遇到了麻烦:因为乘法的存在使得出现了优先级:乘法优先于加法和减法。

    所以我们需要记录上一个操作数:

      e.g.1 a+b*c 上一个操作数就是 b*c 

      e.g.2 b*c + a上一个操作数就是a

      e.g. 3 b*c -a 上一个操作数就是-a

    这里参考了Hcisly的解法(在下面回复中)

    void dfs(string& s, int target, int pos, long cv, long pv, string r, vector<string>& res)

    s : 给出的数字

    target: 目标值

    pos: 起始位置

    cv: 当前的累计值

    pv: 上一个操作数的值

    注意pv的符号!

    代码:

    class Solution {
    public:
        vector<string> addOperators(string num, int target) {
            vector<string> ret;
            dfs(num, target, 0, 0, 0, "", ret);
            return ret;
        }
        
        void dfs(string& s, int target, int pos, long cv, long pv, string r, vector<string>& res) {
            if (pos == s.size() && cv == target) {
                res.push_back(r);
                return;
            }
            for (int i = 1; i <= s.size() - pos; i++) {
                string t = s.substr(pos, i);
                if (i > 1 && t[0] == '0') break; // preceding 
                long n = stol(t);
                if (pos == 0) {
                    dfs(s, target, i, n, n, t, res);
                    continue;
                }
                dfs(s, target, pos+i, cv+n, n, r+"+"+t, res);
                dfs(s, target, pos+i, cv-n, -n, r+"-"+t, res);
                dfs(s, target, pos+i, cv-pv+pv*n, pv*n, r+"*"+t, res);
            }
        }
    };
  • 相关阅读:
    柔性数组成员 (flexible array member)-C99-ZZ
    如何阅读 Redis 源码?ZZ
    linux下网络编程学习——入门实例ZZ
    leetcode Ch2-Dynamic Programming [2014]
    leetcode Ch1-search 2014
    Skip List & Bloom Filter
    指针的引用-ZZ
    leetcode-sudoku solver
    rest framework之过滤组件
    rest framework之渲染器
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9292416.html
Copyright © 2011-2022 走看看