Different Ways to Add Parentheses解题报告

Description:

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:

Input: "2-1-1".
((2-1)-1) = 0
(2-(1-1)) = 2
Output: [0, 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]

Link:

https://leetcode.com/problems/different-ways-to-add-parentheses/description/

解题方法:

分治算法。

Tips:

先遍历一遍字符串将数字储存好。

Time Complexity:

O(N^3)

完整代码:

vector diffWaysToCompute(string input) 
    {
        vector trf;
        if(input.size() == 0)
            return {};
        string temp;
        for(char ch: input)
        {
            if(ch == '+' || ch == '-' || ch == '*')
            {
                trf.push_back(std::atoi(temp.c_str()));
                temp.clear();
                trf.push_back(ch * -1);
            }
            else
                temp += ch;
        }
        trf.push_back(std::atoi(temp.c_str()));
        return helper(0, trf.size() - 1, trf);
    }
vector helper(int start, int end, vector& trf)
    {
        if(start == end)
            return {trf[start]};
        vector result;
        for(int i = start; i <= end; i++)
        {
            if(trf[i] < 0)
            {
                vector left = helper(start, i - 1, trf);
                vector right = helper(i + 1, end, trf);
                for(int l: left)
                {
                    for(int r: right)
                    {
                        switch(trf[i])
                        {
                            case -'+':
                                result.push_back(l + r);
                                break;
                            case -'-':
                                result.push_back(l - r);
                                break;
                            case -'*':
                                result.push_back(l * r);
                                break;
                        }
                    }
                }
            }
        }
        return result;
    }

你可能感兴趣的:(Different Ways to Add Parentheses解题报告)