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 -> []
Solution(Not mine)
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;
}
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;
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);
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 );
}
}
}
}
Solution
public class Solution {
public List<String> addOperators(String num, int target) {
List<String> ans = new ArrayList<String>();
if(num.length() == 0) return ans;
int[] oper = new int[num.length()];
dfs(num.toCharArray(), 0, oper, ans, target);
return ans;
}
public final int EMP = 0;
public final int ADD = 1;
public final int SUB = 2;
public final int MUL = 3;
public void dfs(char[] num, int idx, int[] oper, List<String> ans, int target) {
if(idx == num.length - 1) {n
if(eval(num, oper, target)) {
ans.add(build(num, oper));
}
return;
}
for(int i = 0; i < 4; i++) {
oper[idx] = i;
dfs(num, idx + 1, oper, ans, target);
}
}
public boolean eval(char[] num, int[] oper, int target) {
int lastOp = ADD;
Stack<Long> stack = new Stack<Long>();
long current = 0;
for(int i = 0; i < oper.length; i++) {
if(current == 0 && num[i] == '0' && (i != oper.length-1 && oper[i] == EMP) ) return false;
current = 10 * current + (num[i] - '0');
if(i == oper.length - 1 || oper[i] == ADD || oper[i] == SUB || oper[i] == MUL) {
if(lastOp == ADD) stack.push(current);
else if(lastOp == SUB) stack.push(-current);
else if(lastOp == MUL) {
stack.push(stack.pop() * current);
}
current = 0;
lastOp = oper[i];
}
}
while(!stack.isEmpty()) {
current += stack.pop();
}
return current == target;
}
public String build(char[] num, int[] oper) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < oper.length; i++) {
sb.append(num[i]);
if(i != oper.length - 1 && oper[i] != EMP) {
sb.append(oper[i] == ADD ? '+' : (oper[i] == SUB ? '-' : '*') );
}
}
return sb.toString();
}
}