在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given a string that contains only digits Example 1: Input:
Example 2: Input:
Example 3: Input:
Example 4: Input:
Example 5: Input:
给定一个仅包含数字 示例 1: 输入:
示例 2: 输入:
示例 3: 输入:
示例 4: 输入:
示例 5: 输入:
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 }
|
请发表评论