282. Expression Add Operators
Input:
num = "123",
target= 6
Output: ["1+2+3", "1*2*3"]Input:
num = "232",
target = 8
Output: ["2*3+2", "2+3*2"]Input:
num = "105",
target = 5
Output: ["1*0+5","10-5"]Last updated
Was this helpful?
Input:
num = "123",
target= 6
Output: ["1+2+3", "1*2*3"]Input:
num = "232",
target = 8
Output: ["2*3+2", "2+3*2"]Input:
num = "105",
target = 5
Output: ["1*0+5","10-5"]Last updated
Was this helpful?
Was this helpful?
Input:
num = "00",
target = 0
Output: ["0+0", "0-0", "0*0"]Input:
num = "3456237490",
target = 9191
Output: []class Solution {
public List<String> addOperators(String num, int target) {
List<String> ans = new ArrayList<>();
if(num == null || num.length()== 0) return ans;
dfs(ans, num, "", target, 0, 0, 0);
return ans;
}
private void dfs(List<String> ans, String num, String path, int target, int depth, long eval, long lastAdd){
if(depth == num.length()){
if(eval == target) ans.add(path);
return;
}
for(int i = depth; i < num.length(); i++){
// substring the operand, excluding the leading '0' ones
if(i > depth && num.charAt(depth) == '0') break;
long cur = Long.parseLong(num.substring(depth, i + 1)); //[depth... i]
// global first operand
if(depth == 0){
dfs(ans, num , Long.toString(cur), target, i + 1, cur, cur); // leading element
}
else{
//add
dfs(ans,num,path + "+" + cur, target, i + 1, eval + cur, cur);
//subtract
dfs(ans,num,path + "-" + cur, target, i + 1, eval - cur, -cur);
//multiply
dfs(ans,num,path + "*" + cur, target, i + 1, eval - lastAdd + lastAdd * cur, lastAdd * cur);
}
}
}
}