leetcode282 : Expression Add Operators

1、原題如下:
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 -> []

2、解題如下:

class Solution {
public:
    void dfs(vector<string>& result, const string num, const int target, int pos, string os, const long calres, const char lo, const long ln)
    {
        if (pos == num.size() && calres == target)
            result.push_back(os);
        else
        {
            for (int i = pos + 1; i <= num.size(); i++)
            {
                string nos = num.substr(pos, i - pos);
                long nol = stol(nos);
                if (to_string(nol).size() != i - pos) continue;
                dfs(result, num, target, i, os + '+' + nos, calres + nol, '+', nol);
                dfs(result, num, target, i, os + '-' + nos, calres - nol, '-', nol);
                dfs(result, num, target, i, os + '*' + nos, (lo == '+') ? (calres - ln + ln*nol) : (lo == '-') ? (calres + ln - ln*nol) : ln*nol, lo, ln*nol);
            }
        }
    }
    //fos:first operational string
    //fol:first operational long
    //nos:next  operational string
    //nol:next  operational long
    //lo:last operator
    //ln:last number
    vector<string> addOperators(string num, int target) {
        vector<string> result;
        if (!num.size())  return result;
        for (int i = 1; i <= num.size(); i++)
        {
            string fos = num.substr(0, i);//切割出第一個操作數
            long fol = stol(fos);
            if (to_string(fol).size() != i) continue;
            dfs(result, num, target, i, fos, fol, ' ', fol);//(point1)

        }
        return result;
    }
};

3、總結
這道題主要用的是dfs深度檢索,遍歷所有可能出現的情況。其實我們設想,如果num.size()爲9,那就相當於有八個地方可以添加符號,我們可以選擇填或者不填,雖然每兩個數之間只能填一個操作符,但是總共填多少個並不限制,如此就會有很多種情況。point1之前首先確定第一個操作數,至於它到底有幾位,我們根據循環來逐次遍歷。然後啓動dfs遍歷功能,然後循環迭代,考慮下一個添加符號的位置在哪裏(還是逐次遍歷)操作完所有數之後就進行判斷,看是否計算結果符合,符合就插入,不符合就繼續之前的dfs~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章