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

282 Expression Add Operators 给表达式添加运算符

时间:2018-04-09 21:18:28      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:problem   etc   字符串   highlight   str   int   next   html   数字   

给定一个仅包含0-9的字符串和一个目标值,返回在数字之间添加了二元运算符(不是一元的) +、-或*之后所有能得到目标值的情况。
例如:
"123", 6 -> ["1+2+3", "1*2*3"]
"232", 8 -> ["2*3+2", "2+3*2"]
"105", 5 -> ["1*0+5","10-5"]
"00", 0 -> ["0+0", "0-0", "0*0"]
"3456237490", 9191 -> []
详见:https://leetcode.com/problems/expression-add-operators/description/

class Solution {
public:
    vector<string> addOperators(string num, int target) {
        vector<string> res;
        addOperatorsDFS(num, target, 0, 0, "", res);
        return res;
    }
    void addOperatorsDFS(string num, int target, long long diff, long long curNum, string out, vector<string> &res) {
        if (num.size() == 0 && curNum == target) 
        {
            res.push_back(out);
        }
        for (int i = 1; i <= num.size(); ++i) 
        {
            string cur = num.substr(0, i);
            if (cur.size() > 1 && cur[0] == ‘0‘)
            {
                return;
            }
            string next = num.substr(i);
            if (out.size() > 0)
            {
                addOperatorsDFS(next, target, stoll(cur), curNum + stoll(cur), out + "+" + cur, res);
                addOperatorsDFS(next, target, -stoll(cur), curNum - stoll(cur), out + "-" + cur, res);
                addOperatorsDFS(next, target, diff * stoll(cur), (curNum - diff) + diff * stoll(cur), out + "*" + cur, res);
            }
            else 
            {
                addOperatorsDFS(next, target, stoll(cur), stoll(cur), cur, res);
            }
        }
    }
};

 参考:https://www.cnblogs.com/grandyang/p/4814506.html

282 Expression Add Operators 给表达式添加运算符

标签:problem   etc   字符串   highlight   str   int   next   html   数字   

原文地址:https://www.cnblogs.com/xidian2014/p/8762109.html

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