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.git
Example 1:lua
Input: "123", target = 6 Output: ["1+2+3", "1*2*3"] num =
Example 2:spa
Input: "232", target = 8 Output: ["2*3+2", "2+3*2"]num =
Example 3:code
Input: "105", target = 5 Output: ["1*0+5","10-5"]num =
Example 4:blog
Input: "00", target = 0 Output: ["0+0", "0-0", "0*0"] num =
Example 5:遞歸
Input: "3456237490", target = 9191 Output: []num =
分析get
解法是利用遞歸回溯來遍歷全部的可能,可是要注意一些邊界情形。string
public class Solution { public List<String> addOperators(String num, int target) { List<String> rst = new ArrayList<String>(); if(num == null || num.length() == 0) return rst; helper(rst, "", num, target, 0, 0, 0); return rst; }
// eval記錄當前計算結果,multed計算上次計算變化的部分,在選擇乘法時會用到這個 public void helper(List<String> rst, String path, String num, int target, int pos, long eval, long multed){ if(pos == num.length()){ if(target == eval) rst.add(path); return; } for(int i = pos; i < num.length(); i++){ if(i != pos && num.charAt(pos) == '0') break; // 拋棄以0開始的數字 long cur = Long.parseLong(num.substring(pos, i + 1)); if(pos == 0){ helper(rst, path + cur, num, target, i + 1, cur, cur); // 起始數字特殊處理 } else{ helper(rst, path + "+" + cur, num, target, i + 1, eval + cur , cur); // 對當前數字cur選擇加上以前的部分 helper(rst, path + "-" + cur, num, target, i + 1, eval -cur, -cur); // 選擇減
// 選擇乘法要特殊處理,減去上次變化的部分,將這個變化的部分乘以當前的數字再加上去 helper(rst, path + "*" + cur, num, target, i + 1, eval - multed + multed * cur, multed * cur ); } } } }