-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path241.Different Ways to Add Parentheses.swift
55 lines (47 loc) · 1.52 KB
/
241.Different Ways to Add Parentheses.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import Foundation
/**
* Definition for a binary tree node.
*/
// public class TreeNode {
// public var val: Int
// public var left: TreeNode?
// public var right: TreeNode?
// public init(_ val: Int) {
// self.val = val
// self.left = nil
// self.right = nil
// }
//}
/*
*/
class Solution {
func diffWaysToCompute(_ input: String) -> [Int] {
var result = [Int]();
//判断是否只有数字,递归运算后最后会拆分只剩下数字
if let num = Int(input) {
result.append(num);
}
for index in input.indices {
let c = input[index];
if c == "+" || c == "-" || c == "*" {
//以运算符号为分隔,前面字符串和后面字符串分别计算结果,返回值两两组合
for a in diffWaysToCompute(String(input[input.startIndex ..< index])) {
for b in diffWaysToCompute(String(input[input.index(index, offsetBy: 1) ..< input.endIndex])) {
if c == "+" {
result.append(a+b);
}
else if c == "-" {
result.append(a-b);
}
else if c == "*" {
result.append(a*b);
}
}
}
}
}
return result;
}
}
let s = Solution();
print(s.diffWaysToCompute("2*3-4*5"))