Last updated
Was this helpful?
Last updated
Was this helpful?
Given a string that contains only digits0-9
and a target value, return all possibilities to addbinaryoperators (not unary)+
,-
, or*
between the digits so they evaluate to the target value.
Examples:
(1) Backtracking
思路: 这道题主要就是用Backtracking枚举所有可能的结果,但要注意的edge cases和要处理的问题有:
1.以0开头的非个位数,比如01, 012,这些都是invalid的遇到时我们要直接跳过
2.乘法的优先级会高于加减法,比如2+3*4这种情况,我们按顺序2 + 3的话会得到5,但遇到乘号是,我们要减去3,然后用3乘以4得到12再加回2才等到正确的结果14,所以我们在backtracking的过程中,我们要维护prevNum这个变量记录之前的数,以及curRes记录当前的结果,如果遇到乘号时,curRes先减去prevNum,然后再加上prevNum * curNum。
时间复杂度O(n * 4^(n - 1)), n为num的长度,在num之间有n - 1个slot,对于每个slot我们有4种选择,不插入任何operator,插入3种(+, -, *)operators,对于遍历num的每个位置,我们都要O(4^(n - 1))的时间,总共有n步,所以需要O(n * 4^(n - 1)), 空间复杂度O(n), 递归的深度为n