码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】241. Different Ways to Add Parentheses

时间:2016-07-25 14:34:25      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
unordered_map<string, vector<int> > book;

class Solution { 
public:
    vector<int> diffWaysToCompute(string input) {
        if(book.count(input)) return book[input];
        vector<int> outputs;
        int n = input.length();
        for (int i = 0; i < n; i++) {
            if (input[i] == + || input[i] == - || input[i] == *) {
                string left = input.substr(0, i);
                string right = input.substr(i + 1, n - i - 1);
                vector<int> lval = diffWaysToCompute(left);
                vector<int> rval = diffWaysToCompute(right);
                for (int l : lval) {
                    for (int r : rval) {
                        switch (input[i]) {
                            case +:
                                outputs.push_back(l + r);
                                break;
                            case -:
                                outputs.push_back(l - r);
                                break;
                            default:
                                outputs.push_back(l * r);
                        }
                    } 
                }
            }
        }
        if (outputs.empty())
            outputs.push_back(stoi(input));
        book[input] = outputs;
        return outputs;
    }
};
View Code

 

【LeetCode】241. Different Ways to Add Parentheses

标签:

原文地址:http://www.cnblogs.com/mmyz-sysu-panjn/p/LeetCode241.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!