★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-szoexzfz-kx.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★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.git
Example 1:github
Input: "123", target = 6 Output: ["1+2+3", "1*2*3"] num =
Example 2:微信
Input: "232", target = 8 Output: ["2*3+2", "2+3*2"]num =
Example 3:app
Input: "105", target = 5 Output: ["1*0+5","10-5"]num =
Example 4:lua
Input: "00", target = 0 Output: ["0+0", "0-0", "0*0"] num =
Example 5:spa
Input: "3456237490", target = 9191 Output: []num =
給定一個僅包含數字 0-9
的字符串和一個目標值,在數字之間添加二元運算符(不是一元)+
、-
或 *
,返回全部可以獲得目標值的表達式。code
示例 1:htm
輸入: "123", target = 6 輸出: ["1+2+3", "1*2*3"] num =
示例 2:blog
輸入: "232", target = 8 輸出: ["2*3+2", "2+3*2"]num =
示例 3:
輸入: "105", target = 5 輸出: ["1*0+5","10-5"]num =
示例 4:
輸入: "00", target = 0 輸出: ["0+0", "0-0", "0*0"] num =
示例 5:
輸入: "3456237490", target = 9191 輸出: []num =
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 }