282. Expression Add Operators

Posted ruruozhenhao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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/

 

以上是关于282. Expression Add Operators的主要内容,如果未能解决你的问题,请参考以下文章

java 282. Expression Add Operators.java

java 282. Expression Add Operators.java

java 282. Expression Add Operators.java

java 282. Expression Add Operators.java

java 282. Expression Add Operators.java

java 282. Expression Add Operators.java