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.
Example 1:
Input: num =
"123", target = 6
Output: ["1+2+3", "1*2*3"]
Example 2:
Input: num =
"232", target = 8
Output: ["2*3+2", "2+3*2"]
Example 3:
Input: num =
"105", target = 5
Output: ["1*0+5","10-5"]
Example 4:
Input: num =
"00", target = 0
Output: ["0+0", "0-0", "0*0"]
Example 5:
Input: num =
"3456237490", target = 9191
Output: []
Accepted
89,424
Submissions
257,426
--------------------------------------------------------------------------------------
这题目并不像24点一样可以加括号,所以递推时加减过的表达式不能再去乘,这点一定要明确,写得过程中思路很清晰,但是坑不少,自己的解法用了大量的set,所以会偏慢,以下是自己的解法:
class Solution:
def addOperators(self, num, target):
l,res = len(num),[]
if (l == 0):
return res
exps = [[set() for j in range(l)] for i in range(l)]
for i in range(l):
exps[i][i].add((num[i],int(num[i]),0))
for w in range(2,l+1):
for i in range(0,l+1-w):
j = i+w-1
for mid in range(i,j):
lset,rset = exps[i][mid],exps[mid+1][j]
if (num[i] != '0'): #bug1: forget
exps[i][j].add((num[i:j+1],int(num[i:j+1]),0))
ops = ['+','-','*'] if i == 0 else ['*']
for ll in lset:
for rr in rset:
for op in ops:
if (op == '+'):
exps[i][j].add((ll[0]+'+'+rr[0], ll[1]+rr[1], 1))
elif (op == '-'):
exps[i][j].add((ll[0]+'-'+rr[0], ll[1]-rr[1], 1))
elif (op == '*' and ll[2] == 0): #bug2: miss ll[2] == 0
exps[i][j].add((ll[0]+'*'+rr[0], ll[1]*rr[1], 0))
for exp in exps[0][l-1]:
if (exp[1] == target):
res.append(exp[0])
return res
s = Solution()
print(s.addOperators(num = "00", target = 0))
从Discussion看到的别人的解法:
class Solution {
public:
vector<string> addOperators(string num, int target) {
vector<string> res;
dfs(num, target, 0, 0, 0, "", res);
return res;
}
void dfs(string& s, int target, int pos, long cv, long pv, string r, vector<string>& res) {
if (pos == s.size() && cv == target) {
res.push_back(r);
return;
}
for (int i = 1; i <= s.size() - pos; i++) {
string t = s.substr(pos, i);
if (i > 1 && t[0] == '0') continue; // preceding
long n = stol(t);
if (pos == 0) {
dfs(s, target, i, n, n, t, res);
continue;
}
dfs(s, target, pos+i, cv+n, n, r+"+"+t, res);
dfs(s, target, pos+i, cv-n, -n, r+"-"+t, res);
dfs(s, target, pos+i, cv-pv+pv*n, pv*n, r+"*"+t, res);
}
}
};