Description:
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.
Explanation:
"123", 6 -> ["1+2+3", "1*2*3"]
"232", 8 -> ["2*3+2", "2+3*2"]
"105", 5 -> ["1*0+5","10-5"]
"00", 0 -> ["0+0", "0-0", "0*0"]
"3456237490", 9191 -> []
Solution:
DFS(Depth-first-search).
找出所有可能的情况,涉及到多种组合方式,对每一条分支(组合方式)都要进行深度搜索,直至不能深入,所以采用深度优先搜索。
首先建立一个list来存储结果。建立dfs函数来搜索所有情况。搜索过程中先截取字符串,作为当前操作的数值,然后分别匹配+ - * 三种运算,要注意计算的优先级,所以计算乘法时,要回溯。其次要注意特殊情况,0可以单独作为操作数,但是不可以在多位数中占首位;第一次计算时,当前表达式为空,前边不添加计算符。
public class Solution {
/**
* @param num a string contains only digits 0-9
* @param target an integer
* @return return all possibilities
* Author:Sunday0904
*/
ArrayList<String> result = new ArrayList<String>();
public List<String> addOperators(String num, int target) {
// Write your code here
DFS(num , target , "" , 0 , 0);
return result;
}
public void DFS(String num , int target , String temp , long curResult , long preNum){
if(curResult == target && num.length() == 0){
String expression = new String(temp);
result.add(expression);
return ;
}
for(int i = 1;i<=num.length();i++){
String curStr = num.substring(0 , i);
if(curStr.length() > 1 && curStr.startsWith("0")){
return ;
}
String newNum = num.substring(i);
long curNum = Long.parseLong(curStr);
if(temp.length() == 0){
DFS(newNum , target , curStr , curNum , curNum);
}else{
DFS(newNum , target , temp + "+" + curStr , curResult + curNum , curNum);
DFS(newNum , target , temp + "-" + curStr , curResult - curNum , -curNum);
DFS(newNum , target , temp + "*" + curStr , curResult - preNum + preNum * curNum , preNum * curNum);
}
}
}
}