|
| 1 | +''' |
| 2 | +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. |
| 3 | +
|
| 4 | +Example 1: |
| 5 | +
|
| 6 | +Input: num = "123", target = 6 |
| 7 | +Output: ["1+2+3", "1*2*3"] |
| 8 | +
|
| 9 | +Example 2: |
| 10 | +
|
| 11 | +Input: num = "232", target = 8 |
| 12 | +Output: ["2*3+2", "2+3*2"] |
| 13 | +
|
| 14 | +Example 3: |
| 15 | +
|
| 16 | +Input: num = "105", target = 5 |
| 17 | +Output: ["1*0+5","10-5"] |
| 18 | +
|
| 19 | +Example 4: |
| 20 | +
|
| 21 | +Input: num = "00", target = 0 |
| 22 | +Output: ["0+0", "0-0", "0*0"] |
| 23 | +
|
| 24 | +Example 5: |
| 25 | +
|
| 26 | +Input: num = "3456237490", target = 9191 |
| 27 | +Output: [] |
| 28 | +
|
| 29 | +
|
| 30 | +
|
| 31 | +''' |
| 32 | + |
| 33 | +class Solution(object): |
| 34 | + def addOperators(self, num, target): |
| 35 | + """ |
| 36 | + :type num: str |
| 37 | + :type target: int |
| 38 | + :rtype: List[str] |
| 39 | + """ |
| 40 | + res = [] |
| 41 | + if not num: |
| 42 | + return res |
| 43 | + |
| 44 | + for i in xrange(1, len(num)+1): |
| 45 | + if i == 1 or (i > 1 and num[0] != '0'): |
| 46 | + self.find(num[i:], int(num[:i]), target, num[:i], res, int(num[:i])) |
| 47 | + |
| 48 | + return res |
| 49 | + |
| 50 | + def find(self, num, tmpsum, target, tmp, res, last): |
| 51 | + if not num: |
| 52 | + if tmpsum == target: |
| 53 | + res.append(tmp) |
| 54 | + return |
| 55 | + |
| 56 | + for i in xrange(1, len(num)+1): |
| 57 | + if i == 1 or (i > 1 and num[0] != '0'): |
| 58 | + self.find(num[i:], tmpsum + int(num[:i]), target, tmp + '+' + num[:i], res, int(num[:i])) |
| 59 | + self.find(num[i:], tmpsum - int(num[:i]), target, tmp + '-' + num[:i], res, -int(num[:i])) |
| 60 | + self.find(num[i:], tmpsum - last + last * int(num[:i]), target, tmp + '*' + num[:i], res, last * int(num[:i])) |
| 61 | + |
0 commit comments