【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”.

((2-1)-1) = 0
(2-(1-1)) = 2
Output: [0, 2]

Example 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]

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

分析:
这道题的题意是给一个带有数字和运算符的字符串,得到该算式所有可能的答案。
我的思路是使用分治算法。将每个字符串分成两半再通过递归计算,将左右算式可能得到的结果保存在两个向量中,再通过两个for循环加在一起得到所有可能的答案。

代码:

class Solution {
public:
    vector<int> diffWaysToCompute(string input) {
        vector<int> l,r;
        vector<int> result;      //保存算式可能的所有答案
        result.clear();
        int tt;
        int tag = 0;   //标记字符串中是否存在运算符
        for(int i = 0;i<input.length();i++)
        {
            if(input[i] == '+'||input[i] == '*'||input[i] == '-')     //将字符串分成两半通过递归计算
            {
                tag = 1;
                string temp;
                int j;
                for(j = 0;j<i;j++)
                temp += input[j];
                l = diffWaysToCompute(temp);
                temp.clear();
                for(j = 0;j<input.length()-i-1;j++)
                temp += input[j+i+1];
                r = diffWaysToCompute(temp);
                for(int p = 0;p<l.size();p++)
               {
                for(int q = 0;q<r.size();q++)
                {
                    if(input[i] == '+')
                    {
                        tt = l[p]+r[q];
                        result.push_back(tt);
                    }
                    else if(input[i] == '-')
                    {
                        tt = l[p]-r[q];
                        result.push_back(tt);
                    }
                    else if(input[i] == '*')
                    {
                        tt = l[p]*r[q];
                        result.push_back(tt);
                    }
                }
               }

            }


        }
        if(tag == 0)      //该字符串中不存在运算符号
        {
            int num = 0,temp;
            int j = 0;
            for(int i = input.length()-1;i>=0;i--)
            {
                temp = input[j]-'0';
                num += temp*pow(10,i);
                j++;
            }
            result.push_back(num);

        }
        return result;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值