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

【LeetCode】282. Expression Add Operators

时间:2017-05-07 22:06:13      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:operator   回溯   bst   基本   dig   不能   str   express   span   

题目:

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.

Examples:

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

  

题解:

  想了半个小时还是想不出来,卡在乘上了,看了别人的代码,感觉这个处理很巧妙,基本思路和回溯递归差不多

Soution 1 ()

class Solution {
public:
    void helper(string num, vector<string>& res, string s, int target, int pos, long cur, long pre) {
        if(pos == num.size()) {
            if(cur == target) res.push_back(s);
            return;
        }
        for(int i=pos; i<num.size(); i++) {
                 //首字符为0且长度大于1,那么这个字符串不能代表数字
            if(num[pos] == 0 && i>pos) break;
            string str = num.substr(pos, i-pos+1);
            long val = stol(str);
            if(pos == 0) 
                helper(num, res, s+str, target, i+1, val, val);
            else {
                helper(num, res, s+++str, target, i+1, cur+val, val);
                helper(num, res, s+-+str, target, i+1, cur-val, -val);
                helper(num, res, s+*+str, target, i+1, cur-pre+pre*val, pre*val);
            }
        }
    }
    vector<string> addOperators(string num, int target) {
        vector<string> res;
        if(num.size() == 0) return res;
        helper(num, res, "", target, 0, 0, 0);
        return res;    
    }
};

 

【LeetCode】282. Expression Add Operators

标签:operator   回溯   bst   基本   dig   不能   str   express   span   

原文地址:http://www.cnblogs.com/Atanisi/p/6814841.html

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