严氏北美IT公司面试真题汇总和解答论坛
Would you like to react to this message? Create an account in a few clicks or log in to continue.

Expression Add Operators

Go down

Expression Add Operators  Empty Expression Add Operators

Post by Admin Sat Oct 21, 2017 5:34 pm

static List<String> res=new ArrayList<String>();
public static List<String> addOperators(String num, int target) {
DFS(num, target, "", 0, 0);
return res;
}

private static void DFS(String num, int target, String cur, long curRes, long preNum){
if(curRes == target && num.length() == 0){
res.add(new String(cur));
return;
}
for(int i = 1; i <= num.length(); i++){
String curStr = num.substring(0, i);
if(curStr.length() > 1 && curStr.charAt(0) == '0')
return;
long curNum = Long.parseLong(curStr);
String next = num.substring(i);
if(cur.length() != 0){
DFS(next, target, cur+"*"+curNum, (curRes - preNum) + preNum * curNum, preNum * curNum);
DFS(next, target, cur+"/"+curNum, (curRes - preNum) + preNum / curNum, preNum / curNum);
DFS(next, target, cur+"+"+curNum, curRes + curNum, curNum);
DFS(next, target, cur+"-"+curNum, curRes - curNum, -curNum);
} else {
DFS(next, target, curStr, curNum, curNum);
}
}
}


public static void main(String[] args) {
List<String> res=addOperators("321",4);
for(String s: res)
System.out.println(s);
}

Admin
Admin

Posts : 124
Join date : 2017-10-21

https://csinterviewquestions.forumotion.com

Back to top Go down

Back to top


 
Permissions in this forum:
You cannot reply to topics in this forum