282. 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 -> []
其实这题是很简单的,就是用DFS找出所有可能性,只是最最麻烦的是怎么处理前面部分是加减,后面部分是乘的情况。我本来是用逆波兰表达式来计算的,但是下面的解法更方便。
From: https://segmentfault.com/a/1190000003797204
1 public class Solution { 2 public List<String> addOperators(String num, int target) { 3 List<String> resulstsList = new ArrayList<>(); 4 helper(num, target, "", 0, 0, resulstsList); 5 return resulstsList; 6 } 7 8 private void helper(String num, int target, String tmp, long currRes, long prevNum, List<String> res) { 9 if (currRes == target && num.length() == 0) { 10 res.add(tmp); 11 return; 12 } 13 // 搜索所有可能的拆分情况 14 for (int i = 1; i <= num.length(); i++) { 15 String currStr = num.substring(0, i); 16 // 对于前导为0的数予以排除 17 if (currStr.length() > 1 && currStr.charAt(0) == '0') { 18 break; 19 } 20 // 得到当前截出的数 21 long currNum = Long.parseLong(currStr); 22 // 去掉当前的数,得到下一轮搜索用的字符串 23 String next = num.substring(i); 24 // 如果不是第一个字母时,可以加运算符,否则只加数字 25 if (tmp.length() != 0) { 26 // 乘法 27 helper(next, target, tmp + "*" + currNum, (currRes - prevNum) + prevNum * currNum, prevNum * currNum, res); 28 // 加法 29 helper(next, target, tmp + "+" + currNum, currRes + currNum, currNum, res); 30 // 减法 31 helper(next, target, tmp + "-" + currNum, currRes - currNum, -currNum, res); 32 } else { 33 // 第一个数 34 helper(next, target, currStr, currNum, currNum, res); 35 } 36 } 37 } 38 }