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<int> diffWaysToCompute(string input) 
    {
        vector<int> 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<int> helper(int start, int end, vector<int>& trf)
    {
        if(start == end)
            return {trf[start]};
        vector<int> result;
        for(int i = start; i <= end; i++)
        {
            if(trf[i] < 0)
            {
                vector<int> left = helper(start, i - 1, trf);
                vector<int> 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;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,890评论 0 23
  • 我们似乎都有同样的经历,比如,刚刚读过的书,转眼忘记内容。歪着头回忆,昨天那本书说什么来着~(⊙o⊙)…再比如,好...
    絔澜Moe_阅读 307评论 0 1
  • 什川游记是在什川梨花节后一天写的,因为当时的我还没搞清楚去哪里游,说说也是个后序式的笑话。朋友说周末一起去玩,愉快...
    梅园遗珠阅读 633评论 0 0
  • 好 还是不好? 介于两者之间 状态如此 心情亦是如此 我想要知道 康复的时间 可是 不可能 我才发现 原来自己达不...
    休憩中的猫阅读 141评论 0 0
  • 开满荷花的池塘留在了记忆的故乡那浅浅的河湾溢满了我痴迷的欢唱撷一叶荷抛入水的滚烫加入晶莹剔透的冰糖曲线的身姿在壶水...
    昊水长天阅读 533评论 1 10