[Swift]LeetCode282. 给表达式添加运算符 | Expression Add Operators

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10241192.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

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: []

给定一个仅包含数字 0-9 的字符串和一个目标值,在数字之间添加二元运算符(不是一元)+- 或 * ,返回所有能够得到目标值的表达式。

示例 1:

输入: num = "123", target = 6
输出: ["1+2+3", "1*2*3"] 

示例 2:

输入: num = "232", target = 8
输出: ["2*3+2", "2+3*2"]

示例 3:

输入: num = "105", target = 5
输出: ["1*0+5","10-5"]

示例 4:

输入: num = "00", target = 0
输出: ["0+0", "0-0", "0*0"]

示例 5:

输入: num = "3456237490", target = 9191
输出: []

1416ms
 1 class Solution {
 2     func addOperators(_ num: String, _ target: Int) -> [String] {
 3         let numArr = Array(num)
 4         var res = [String]()
 5         
 6         opeHelp(numArr, 0, 0, 0, "", &res, target)
 7         
 8         return res
 9     }
10     
11     func opeHelp(_ numArr : [Character],_ total : Int,_ last : Int , _ index : Int,_ str : String, _ res : inout [String], _ target : Int) {
12         if index == numArr.count {
13             if total == target {
14                 res.append(str)
15             }
16             return
17         }
18         
19         for i in index+1...numArr.count {
20             let tmp = String(numArr[index..<i])
21             let count = tmp.count
22             if count > 1 && numArr[index] == "0" {
23                 continue
24             }
25             
26             let n = Int(tmp)!
27             
28             if index == 0 {
29                 opeHelp(numArr, total + n, n,i, str + tmp, &res, target)
30                 continue
31             }
32             
33             opeHelp(numArr, total + n, n,i, str + "+" + tmp, &res, target)
34             opeHelp(numArr, total - n, -n,i, str + "-" + tmp, &res, target)
35             opeHelp(numArr, (total - last) + last * n, last * n, i,str + "*" + tmp, &res, target)
36         }
37         
38     }
39 }
原文地址:https://www.cnblogs.com/strengthen/p/10241192.html