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.
Example 1:
Input: num =
"123", target = 6
Output: ["1+2+3", "1*2*3"]
Example 2:
Input: num =
"232", target = 8
Output: ["2*3+2", "2+3*2"]
Example 3:
Input: num =
"105", target = 5
Output: ["1*0+5","10-5"]
Example 4:
Input: num =
"00", target = 0
Output: ["0+0", "0-0", "0*0"]
Example 5:
Input: num =
"3456237490", target = 9191
Output: []
解题思路:
没错!时间复杂度就是O(4^n)
DFS
class Solution {
public:
vector<string> addOperators(string num, int target)
{
string exp ;
DFS(num , target , exp , 0 , 0 , 0) ;
return ans ;
}
void DFS(string& num , int target , const string& exp , int pos , long pre , long cur)
{
if(pos == num.size())
{
if(cur == target) ans.push_back(exp) ;
return ;
}
for(int l = 1 ; l <= num.size() - pos ; ++l)
{
string s = num.substr(pos , l) ;
if(l > 1 && s[0] == '0') break ;
long n = stol(s) ;
if(pos == 0)
{
DFS(num , target , exp + s , l , n , n);
continue ;
}
DFS(num , target , exp + '+' + s , pos + l , n , cur+ n) ;
DFS(num , target , exp + '-' + s , pos + l , -n , cur - n) ;
DFS(num , target , exp + '*' + s , pos + l , pre * n , cur - pre + pre * n) ;
}
}
private :
vector<string> ans ;
};
这里有一个C++上的问题。
如果是:void DFS(string& num , int target , string& exp , int pos , long pre , long cur)
DFS(num , target , exp + '+' + s , pos + l , n , cur+ n) 这一行会报错;
如果是void DFS(string& num , int target , const string& exp , int pos , long pre , long cur) 就不会报错。
因为常量引用可以绑定一个临时对象,而非常量引用不可以。exp + '+' + s会隐式转换成一个临时的string对象。