码迷,mamicode.com
首页 > 其他好文 > 详细

282. Expression Add Operators

时间:2019-01-28 19:23:36      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:sub   max   opera   back   length   ++   etc   break   tar   

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

标签:sub   max   opera   back   length   ++   etc   break   tar   

原文地址:https://www.cnblogs.com/ruruozhenhao/p/10331331.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!