题目链接:https://leetcode.com/problems/expression-add-operators/、
题目:
Given a string that contains only digits 0-9
and a target value, return all possibilities to add binaryoperators (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 -> []
题意:给定一个包含0-9的字符串和一个目标值,返回对字符串中字符的所有可能的运算来得到目标值
方法:递归
注意:在运算乘法时应该将前一步运算移除
public class Solution {
public List<String> addOperators(String num, int target) {
List<String> result = new ArrayList<String>();
addOperatorsDFS(num, target, 0, 0, "", result);
return result;
}
public void addOperatorsDFS(String num, int target, long diff, long curNum, String out, List<String> result) {
if(num.length() == 0 && curNum == target) {
result.add(out);
}
for(int i=1; i<=num.length(); i++) {
String cur = num.substring(0,i);
if(cur.length() > 1 && cur.charAt(0) == '0')
return;
String next = num.substring(i);
if(out.length() > 0) {
addOperatorsDFS(next, target, Long.parseLong(cur), curNum + Long.parseLong(cur), out+"+"+cur, result);
addOperatorsDFS(next, target, -Long.parseLong(cur), curNum - Long.parseLong(cur), out+"-"+cur, result);
addOperatorsDFS(next, target, diff*Long.parseLong(cur), curNum - diff + diff*Long.parseLong(cur), out+"*"+cur, result);
} else {
addOperatorsDFS(next, target, Long.parseLong(cur), Long.parseLong(cur), cur, result);
}
}
}
}