282. Expression Add Operators
Last updated
Last updated
dfs for style
Input: num = "123", target = 6
Output: ["1*2*3","1+2+3"]
้ๅฐ 1 2 3 ไธญ้ๅปๅ ็ฎๆธ็ฌฆ่
String curStr = num.substring(0, i+1);
็ชฎ่ๆๆๆธๅญ็ๅฏ่ฝ, ๅปๆญ
curStr:1
nextStr:23 // String nextStr = num.substring(i+1);, ๅฉไธ็
curStr:2
nextStr:3
curStr:3
nextStr:
curStr:3
nextStr:
curStr:3
nextStr:
curStr:23
nextStr:
curStr:12
nextStr:3
curStr:3
nextStr:
curStr:123
nextStr:
for 1
curStr = 1
nextStr = 23
so parse 1 first, save to preStr, preVal
ๆไปฅ +, - ๅพ็ด่งๅฐฑๆฏ
preStr + "+" + curStr, preVal+curVal
preStr + "-" + curStr, preVal-curVal
ไฝ้่ฆๅคไธๅ lastVal, why? for *
## *่
้่ฃกๅฐฑ่ฆๅฉ็จไนๅๆญธ็ดๅบ็็ตๆ
1+23+4*DFS...
preVal ๅ
ๅซไบ 1+23+4 = 28, ไฝๅ
ถๅฏฆ 4ไธๆ่ฉฒ่จ็ฎ้ฒๅป, ๆไปฅ้่ฆ็ด้ lastVal
preVal ่ฆๅชๆ 4(lastVal), ็ถๅพ lastVal ๅจ่ทไนๅพ็ไน,
โ dfs preVal = preVal- lastVal + lastVal * curVal
dfs lastVal ๏ผ lastVal * curVal
ๆณจๆ curStr ็ๅญๆฏ 0้้ ญ้ทๅบฆๅคงๆผ1็, ไธ่็
// 05 ้็จฎๅญไธ่็
if (curStr.charAt(0) == '0' && curStr.length() > 1) {
continue;
}
T: 4 dfs, 4 choice, 4*4*4..., O(4^n), and substing operationis O(n) so O(n*4^n)
S: O(n), dfs stack space
class Solution {
public List<String> addOperators(String num, int target) {
List<String> res = new ArrayList<>();
dfs(res, num, (long)target, "", 0, 0);
return res;
}
private void dfs(List<String> res, String num, long target,
String preStr, long preVal, long lastVal) {
// nextStr ็จ็กๆ, ไธ preVal(pre result) == target
if (num.length() == 0 && preVal == target) {
res.add(preStr);
return;
}
for (int i = 0; i < num.length(); i++) {
String curStr = num.substring(0, i+1);
// in next dfs, use remain string
String nextStr = num.substring(i+1);
// for ["1*0+5","1*05","10-5"] this test case, we should handle "1*05" this case, it's illegal
// 05 ้็จฎๅญไธ่็
if (curStr.charAt(0) == '0' && curStr.length() > 1) {
continue;
}
long curVal = Long.parseLong(curStr);
if ("".equals(preStr)) {
dfs(res, nextStr, target, curStr, curVal, curVal);
} else {
dfs(res, nextStr, target, preStr + "+" + curStr, preVal+curVal, curVal);
dfs(res, nextStr, target, preStr + "-" + curStr, preVal-curVal, -curVal);
dfs(res, nextStr, target, preStr + "*" + curStr, preVal-lastVal + lastVal*curVal, lastVal*curVal);
}
}
}
}
/*
T: 4 dfs, 4 choice, 4*4*4..., O(4^n), and substing operationis O(n) so O(n*4^n)
S: O(n), dfs stack space
1.
for i = curPos+1
substr(curPos, i - curPos)
3 DFS for +, -, *
2.
1 +-* 2 + dfs(345)
preStr currVal
preVal
but * is spaecail, due to mutiply priority
1 + 2 * dfs(345)
1 + 2 cant cal first, so need keep last part of 1 + 2 => 2
dfs() preval =
preVal - lastVal + lastVal*currVal
long preVal, long lastVal => avoid after * to overflow number
3.
terminal condition
curPos == num.length() && preStr == target
4. for ["1*0+5","1*05","10-5"] this test case, we should handle "1*05" this case, it's illegal
*/j