LeetCode-282. Expression Add Operators (JAVA)表达式求值

来源:互联网 发布:csol2控制台fps优化 编辑:程序博客网 时间:2024/06/05 20:15

282. Expression Add Operators

Given a string that contains only digits 0-9 and a target value, return all possibilities to addbinary 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+回溯

本题注意点

1.取数字的时候可能 超过int的范围,用long来处理

2.前导0

3.乘法要记录上次的计算结果并减去

需要这么几个变量,一个是记录上次的计算结果curRes,一个是记录上次被加或者被减的数preNum,一个是当前准备处理的数curNum。当下一轮搜索是加减法时,preNum就是简单换成curNum,当下一轮搜索是乘法时,preNumpreNum乘以curNum

public List<String> addOperators(String num, int target) {List<String> ret = new ArrayList<String>();if (num == null || num.length() == 0)return ret;helper(ret, "", num, target, 0, 0, 0);return ret;}// 问题是取数字的时候可能 超过int的范围,用long来处理public void helper(List<String> ret, String path, String num, int target, int pos, long curRes, long preNum) {if (pos == num.length()) {if (target == curRes)ret.add(path);return;}for (int i = pos; i < num.length(); i++) {// 得到当前截出的数// 对于前导为0的数予以排除,pos为第一位if (i != pos && num.charAt(pos) == '0')return;long curNum = Long.valueOf(num.substring(pos, i + 1));// 处理前导的另一种方法,当前substring长度和curNum长度不等说明有前导0// 处理前导0的情况比如“105”,5一种结果是1*05// if (num.substring(pos, i + 1).length() !=// String.valueOf(curNum).length())// return;// 如果不是第一个字母时,可以加运算符,否则只加数字if (pos == 0) {helper(ret, path + curNum, num, target, i + 1, curNum, curNum);} else {helper(ret, path + "+" + curNum, num, target,i + 1, curRes + curNum, curNum);helper(ret, path + "-" + curNum, num, target, i + 1, curRes - curNum, -curNum);// 注意乘法,因为之前加了preNum,本次要减去!helper(ret, path + "*" + curNum, num, target,i + 1, curRes - preNum + preNum * curNum,preNum * curNum);// if(curNum != 0) helper(ret, num, path + "/" + cur, i+1,// curRes-preNum+preNum/curNum, target, preNum/curNum);}}}



0 0
原创粉丝点击