2017-09-13 LeetCode_241 Different Ways to Add Parentheses

241. Different Ways to Add Parentheses

Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +- and *.


Example 1

Input: "2-1-1".

((2-1)-1) = 0
(2-(1-1)) = 2

Output: [0, 2]


Example 2

Input: "2*3-4*5"

(2*(3-(4*5))) = -34
((2*3)-(4*5)) = -14
((2*(3-4))*5) = -10
(2*((3-4)*5)) = -10
(((2*3)-4)*5) = 10

Output: [-34, -14, -10, -10, 10]

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

Solution:

vector<int> remem[500][500];
2
class Solution {
3
public:
4
    vector<int> divides(string input, int start, int end, int* d) {
5
        vector<int> ans;
6
        if (remem[d[start]][d[end]].size() != 0) return remem[d[start]][d[end]];
7
        if (d[start] == d[end]) {
8
            int x = 0;
9
            for (int i = start; i <= end; i++) x = x*10+input[i]-'0';
10
            ans.push_back(x);
11
            if (d[start] < 500) remem[d[start]][d[end]] = ans;
12
            return ans;
13
        }
14
        for (int k = start; k <= end; k++)
15
            if (input[k] < '0' || input[k] > '9') {
16
                vector<int> left = divides(input, start, k-1, d),
17
                    right = divides(input, k+1, end, d);
18
                for (int i = 0; i < left.size(); i++)
19
                    for (int j = 0; j < right.size(); j++)
20
                        if (input[k] == '+') ans.push_back(left[i]+right[j]);
21
                        else if (input[k] == '-') ans.push_back(left[i]-right[j]);
22
                        else ans.push_back(left[i]*right[j]);
23
            }
24
        if (d[start] < 500 && d[end] < 500) remem[d[start]][d[end]] = ans;
25
        return ans;
26
    }
27
    vector<int> diffWaysToCompute(string input) {
28
        vector<int> ans;
29
        for (int i = 0; i < 500; i++)
30
            for (int j = 0; j < 500; j++)
31
                remem[i][j].clear();
32
        if (input.size() == 0) return ans;
33
        int *p, t = 0;
34
        p = new int[input.length()];
35
        for (int i = 0; i < input.length(); i++) {
36
            p[i] = t;
37
            if (input[i] < '0' || input[i] > '9') t++;
38
        }
39
        ans = divides(input, 0, input.size()-1, p);
40
        delete[] p;
41
        return ans;
42
    }
43
};







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值