leetcode 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"
Output: [0, 2]

Explanation:

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

Example 2:

Input: "2*3-4*5"
Output: [-34, -14, -10, -10, 10]

Explanation:

(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

根据题意,找出所有可能的运算顺序,并输出对应的结果。
在这里可以用分治的思想。若要求对于给定的长度为 n 的string输入,可以先退而求其次,求出给定输入的子列的所有可能的情况。并将子列长度为 1 或 2 时作为最小自问题(不可分割的基本问题)。根据这一指导思想进行程序设计。
首先,将运算符作为分割string的标志,划分为左右两部分。执行递归时应当注意,一个子序列的很可能有很多种,据此,设定递归函数的返回值为数组。合并左右两部分可能的结果时,再按照操作运算计算出所有的结果,即当前递归区间的所有可能


class Solution {
private:
    vector<int> divide(int lo,int hi,string& input){
        vector<int> storeSum;
        for(register int i=lo;i<=hi;i++)
            if(input[i]=='+' || input[i]=='-' || input[i]=='*'){
                vector<int> leftSum=divide(lo,i-1,input);
                vector<int> rightSum=divide(i+1,hi,input);
                for(auto eleL : leftSum)
                    for(auto eleR : rightSum){
                        switch(input[i]){
                            case '+':
                                storeSum.push_back(eleL+eleR);
                                break;
                            case '-':
                                storeSum.push_back(eleL-eleR);
                                break;
                            case '*':
                                storeSum.push_back(eleL*eleR);
                                break;
                        }
                    }
            }
        if(storeSum.size()==0){
            int num=0;
            for(register int i=lo;i<=hi;i++)
                num=num*10+input[i]-'0';
            storeSum.push_back(num);
        }
        return storeSum;
    }
public:
    vector<int> diffWaysToCompute(string input) {
        vector<int> ans;
        if(input.size()==0)
            return ans;
        ans=divide(0,input.size()-1,input);
        return ans;
    }
};

在递归中,不难发现许多区间是重复计算的,因此可以借助map<string,vector< int> >来优化程序


这个暂时没有代码 qwq


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值