[leetcode] 282. Expression Add Operators 解题报告

题目链接:https://leetcode.com/problems/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.

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


思路:今天看到我的有些文章被csdn收入算法和数据结构知识库,我真的很高兴也很惶恐.当初写解题报告只是为了让自己记住当初自己的想法,方便以后回顾,能够帮助别人我自己很高兴,又怕写的不好误导别人.算起来自去年十月份开始写解题报告,到现在leetcode总共331道题已经几乎刷完了,也写了300+的解题报告,我的刷题大业也已经持续了将近八个月之久,有时候想想除了当时考研,我再也没有投入这么多精力到一件事情上.在国外如此繁重的课程压力下我还是一直在坚持.中间找实习除了facebook几乎都没有回音,而facebook也在二面的时候跪了,当时非常沮丧,也认识到自己还差很多.但是生活还是要继续,所以我只能不停的刷题.而在这么长的时间里,我也感到我一直在进步,一方面是算法,另一方面是语言本身.我对c++的理解到现在也比一年前深了很多,马上要开始找全职了,希望我利用好这最后一个暑假拿到一个好的offer.


本题也是一个很好的DFS+回溯的题目,我们要一边搜索,一边记录路径,当搜索到字符串尽头的时候判断是否最后的值等于target值,如果等的话就将路径加入到结果集合中去.另外有二个需要注意是:

1.如果子串是以'0'开头,那么只能以单独的"0"的形式存在

2.如果是乘法那么需要将前面一个数字取出来进行乘法运算,也就是记录的之前的值要回溯这个要乘的数.

代码如下:

class Solution {
public:
    void DFS(string num, int target, string path, int pos, int curVal, int pre)
    {
        if(pos==num.size()) 
        {
            if(target== curVal) result.push_back(path); 
            return;
        }
        long n =0;
        for(int i = pos; i<num.size(); i++)
        {
            n = 10*n + (num[i]-'0');
            if(n > INT_MAX) return;
            if(pos ==0) DFS(num, target, to_string(n), i+1, n, n);
            else
            {
                DFS(num, target, path+"+"+to_string(n), i+1, curVal+n, n);
                DFS(num, target, path+"-"+to_string(n), i+1, curVal-n, -n);
                DFS(num, target, path+"*"+to_string(n), i+1, curVal-pre+pre*n,pre*n);
            }
            if(num[pos] == '0') return;
        }
    }
    
    vector<string> addOperators(string num, int target) {
        if(num.size()==0) return result;
        string path;
        DFS(num, target, path, 0, 0, 0);
        return result;
    }
private:
    vector<string> result;
};
参考:https://leetcode.com/discuss/58614/java-standard-backtrace-ac-solutoin-short-and-clear




你可能感兴趣的:(LeetCode,String,DFS)