Showing posts with label Divide and Conquer. Show all posts
Showing posts with label Divide and Conquer. Show all posts

Monday, October 30, 2017

241. Different Ways to Add Parentheses

https://leetcode.com/problems/different-ways-to-add-parentheses/description/
    vector<int> diffWaysToCompute(string input) {
        vector<int> res;
        int pos = 0;
        while((pos = input.find_first_of("+-*", pos + 1)) != string::npos) {
            vector<int> res1 = diffWaysToCompute(input.substr(0, pos));
            vector<int> res2 = diffWaysToCompute(input.substr(pos + 1));
            for(int& a : res1)
                for(int& b : res2)
                    switch(input[pos]) {
                        case '+': res.push_back(a + b);
                            break;
                        case '-': res.push_back(a - b);
                            break;
                        default: res.push_back(a * b);
                            break;
                    }
        }
        if(res.size() == 0) res.push_back(stoi(input));
        return res;
    }