本文主要是介绍Expression Add Operators,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一道求集合的dfs题。有很多的要注意的地方:
1. 为了处理,
"3456237490", 9191 -> []我们得用long来处理数字,表现在:
long curNum = Long.valueOf(curStr);
2. i是小于等于num的size,
i <= num.length()
3. 对于乘法,要理解以下,来求解当前的结果
curRes - prevNum + prevNum * curNum
4. 对于第一个数字,直接将当前数字带入之后计算。
helper(list, nextNum, target, curStr, curNum, curNum);
public class Solution {public List<String> addOperators(String num, int target) {List<String> list = new LinkedList<>();helper(list, num, target, "", 0, 0);return list;}//private void helper(List<String> list, String num, int target, String temp, int curRes, int prevNum) {private void helper(List<String> list, String num, int target, String temp, long curRes, long prevNum) {if (curRes == target && num.length() == 0) {list.add(new String(temp));return ;}//for (int i = 1; i < num.length(); i++) {for (int i = 1; i <= num.length(); i++) {String curStr = num.substring(0, i);if (curStr.length() > 1 && curStr.charAt(0) == '0') {return;}//int curNum = Integer.valueOf(curStr);long curNum = Long.valueOf(curStr);String nextNum = num.substring(i);if (temp.length() != 0) {helper(list, nextNum, target, temp + '*' + curNum, curRes - prevNum + prevNum * curNum, prevNum * curNum);helper(list, nextNum, target, temp + '+' + curNum, curRes + curNum, curNum);helper(list, nextNum, target, temp + '-' + curNum, curRes - curNum, -curNum);} else {helper(list, nextNum, target, curStr, curNum, curNum);}}}
}
这篇关于Expression Add Operators的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!