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/

 

posted @ 2019-01-28 18:27  Veritas_des_Liberty  阅读(145)  评论(0编辑  收藏  举报