1. 程式人生 > >【LeetCode】282. 給表示式新增運算子 結題報告 (C++)

【LeetCode】282. 給表示式新增運算子 結題報告 (C++)

原題地址:https://leetcode-cn.com/problems/expression-add-operators/

題目描述:

給定一個僅包含數字 0-9 的字串和一個目標值,在數字之間新增二元運算子(不是一元)+、- 或 * ,返回所有能夠得到目標值的表示式。

示例 1:

輸入: num = "123", target = 6
輸出: ["1+2+3", "1*2*3"] 
示例 2:

輸入: num = "232", target = 8
輸出: ["2*3+2", "2+3*2"]
示例 3:

輸入: num = "105", target = 5
輸出: ["1*0+5","10-5"]
示例 4:

輸入: num = "00", target = 0
輸出: ["0+0", "0-0", "0*0"]
示例 5:

輸入: num = "3456237490", target = 9191
輸出: []

 

解題方案:

分治演算法,實現方式是深度優先遍歷 。。苦澀 ,還是不能像廣度優先遍歷掌握的那麼好,置頂留著學習了。

程式碼 :

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);
        }
    }
};