不是很好理解,有点繁杂~~须再咀嚼。
class Solution {
public List<String> addOperators(String num, int target) {
List<String> res=new ArrayList<>();
if(num.length()==0) return res;
helper(num,target,"",res,0,0,0);
return res;
}
public void helper(String num, int target,String path,List<String> res,int position,long evaluated,long multiplied ){
if(position==num.length()&&evaluated==target) res.add(path);
else{
for(int i=position;i<num.length();i++){
if(i!=position&&num.charAt(position)=='0') break;
long current=Long.parseLong(num.substring(position,i+1));
if(position==0) helper(num,target,path+current,res,i+1,evaluated+current,current);
else{
helper(num,target,path+"+"+current,res,i+1,evaluated+current,current);
helper(num,target,path+"-"+current,res,i+1,evaluated-current,-current);
helper(num,target,path+"*"+current,res,i+1,evaluated-multiplied+multiplied*current,multiplied*current);
}
}
}
}
}