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 -> []

public class Solution {
private void dfs(List<String> ret, char[] path, int len, long left, long cur, char[] digits, int pos, int target) {
if (pos == digits.length) {
if (left + cur == target) ret.add(new String(path, 0, len));
return;
}
long n = 0;
int j = len + 1;
for (int i = pos; i < digits.length; i++) {
n = n * 10 + digits[i] - '0';
path[j++] = digits[i];
path[len] = '+';
dfs(ret, path, j, left + cur, n, digits, i + 1, target);
path[len] = '-';
dfs(ret, path, j, left + cur, -n, digits, i + 1, target);
path[len] = '*';
dfs(ret, path, j, left, cur * n, digits, i + 1, target);
if (digits[pos] == '0') break;
}
}
public List<String> addOperators(String num, int target) {
if (num.length() == 0) return ret;
char[] path = new char[num.length() * 2 - 1];
char[] digits = num.toCharArray();
long n = 0;
for (int i = 0; i < digits.length; i++) {
n = n * 10 + digits[i] - '0';
path[i] = digits[i];
dfs(ret, path, i + 1, 0, n, digits, i + 1, target);
if (n == 0) break;
}
return ret;
}
}

18ms,beats 98.68%,241ms,2.21%
cmershen的碎碎念：

• 本文已收录于以下专栏：

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

• mine_song
• 2017年04月30日 17:35
• 271

Given a string that contains only digits 0-9 and a target value, return all possibilities to add b...
• ER_Plough
• 2015年09月21日 11:26
• 1226

Given a string that contains only digits 0-9 and a target value, return all possibilities to add b...
• tingting256
• 2015年10月24日 14:27
• 551

• revoir
• 2016年04月16日 14:05
• 347

## [LeetCode 282] Expression Add Operator

Given a string that contains only digits 0-9 and a target value, return all possibilities to add bi...
• sbitswc
• 2015年10月09日 13:31
• 2265

Expression Add Operators  My Submissions Question Solution  Total Accepted: 1506 Total Submissions: ...
• u013027996
• 2015年09月24日 17:19
• 3263

• xiaocong1990
• 2017年08月25日 15:15
• 71

## Leetcode 282. Expression Add Operators

282. Expression Add Operators Total Accepted: 17890 Total Submissions: 65879 Difficulty: Hard ...
• fantasiasango
• 2016年10月07日 23:19
• 242

## leetcode 282. Expression Add Operators

282. Expression Add Operators Given a string that contains only digits 0-9 and a target value, ...
• liqinzhe11
• 2017年11月28日 20:24
• 56