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

題目是一道比較明顯的回溯題目,主要邊界點有:
1、String格式轉爲數溢出問題,採用long解決
2、連0開頭的數比如001是無效的問題

因爲有乘法,所以用到了一個技巧,從而可以在遞歸中解決乘法。
比如一個式子 1 + 2 * 3,我們在遞歸回溯的時候,先計算的是 1 + 2 = 3記爲 val,而把 2 記爲 mult,也就是下一輪中如果有乘法,那麼要拿 mult作爲一個乘數 ,下一輪出現一個乘法,那麼val - mult 就相當於回退上一輪的加法操作,而 mult * cur 就是把上一輪的乘數乘到本輪,即本輪求出的結果是 val - mult + mult * cur. 同樣對於減法和乘法,mult的值要進行相應改變。

回溯的思路比較簡單,就是每一輪從一個位置開始,選一個位置加入 +,-,*進行遞歸,但是乘法的trick不容易想到。

代碼如下:

public class Solution {
    private String num;
    public List<String> addOperators(String num, int target) {
        List<String> result = new ArrayList<>();
        if (num == null || num.length() == 0) return result;
        this.num = num;
        helper(result,target,"",0,0,0);
        return result;
    }

    private void helper(List<String> res, int target, String path, int pos, long val, long mult) {
        if (pos == num.length()) {
            if (target == val) {
                res.add(path);
                return;
            }
        }
        for (int i = pos;i<num.length();i++) {
            if (i != pos && num.charAt(pos) == '0') break;
            long cur = Long.parseLong(num.substring(pos,i + 1));
            if (pos == 0)
                helper(res,target,path + cur,i + 1,cur,cur);
            else {
                helper(res,target,path + "+" + cur,i + 1,val + cur,cur);
                helper(res,target,path + "-" + cur,i + 1,val - cur,-cur);
                helper(res,target,path +"*" + cur,i + 1,val - mult + mult * cur,mult * cur);
            }
        }
    }
}
發佈了57 篇原創文章 · 獲贊 21 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章