Leetcode——241. 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 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]

solution

这一题挺难的,反正思想就是递归求解。递归可以把前后两部分从i位置处分开,然后依次计算前一部分和后一部分的各种可能的解。
递归的设计不太好想!

class Solution {
public:
    vector<int> diffWaysToCompute(string input) {
         if(input.size()==0) return {};
         vector<int>res;
         for(int i=0;i<input.size();i++)
         {
             if(input[i]!='*'&&input[i]!='+'&&input[i]!='-') continue;
             vector<int> tem1=diffWaysToCompute(input.substr(0,i));
             auto tem2=diffWaysToCompute(input.substr(i+1));
             for(auto vec1:tem1)
                for(auto vec2:tem2)
                {
                    switch(input[i])
                    {
                        case '+':
                            res.push_back(vec1+vec2);
                            break;
                        case '-':
                            res.push_back(vec1-vec2);
                            break;
                        case '*':
                            res.push_back(vec1*vec2);
                            break;
                        default:
                            break;
                    }
                }
         }
         if(res.size()==0)
            return vector<int>{stoi(input)};
        else
            return res;
    }
};

自己写的不对的代码:
每次求取两个数的运算,把n个数的运算转化为n-1个,依次递减到2个数的运算。
但是存在重复的问题:
写了半天,也粘贴出来:

class Num241 {//递归求解
public:
    vector<int> diffWaysToCompute(string input) {
        vector<int> res;

        vector<int> num;
        vector<char>ope;
        int i = 0;
        while (i<input.length())
        {
            int a = 0;
            int sign = 1;
            while (i<input.length() && (isdigit(input[i]) || (input[i] == '-' && (!isdigit(input[i + 1])))))//类似2-1这种
            {
                if (input[i] == '-') sign = -1;
                else
                    a = a * 10 + (input[i] - '0');
                i++;
            }
            num.push_back(a);
            if (i<input.length())
                ope.push_back(input[i]);
            i++;
        }
        int count = num.size();
        helper(res, num, ope);
        return res;
        //unordered_map<int,int> resres;
        //unordered_map<int, int>::iterator it;
        //for (int i = 0;i < res.size();i++)
        //{
        //      resres[res[i]] = 1;
        //}
        //vector<int> newres;
        //for (it = resres.begin();it != resres.end();it++)
        //  newres.push_back(it->first);
        //return newres;
    }
private:
    void helper(vector<int>& res, vector<int> num, vector<char>ope)
    {
        if (num.size() == 2)
        {
            int a = num[0], b = num[1];
            cout <<"res"<< a << " " << b <<" "<< ope[0]<<endl;
            switch (ope[0])
            {
            case '+':
                res.push_back(a + b);
                break;
            case '-':
                res.push_back(a - b);
                break;
            case '*':
                res.push_back(a*b);
                break;
            default:
                break;
            }
            //return;
        }
        else
        {

            for (int i = 0; i<num.size() - 1; i++)//
            {
                int temp = 0;
                int a = num[i], b = num[i + 1];
                cout << a << " " << b << endl;
                switch (ope[i])
                {
                case '+':
                    temp = a + b;
                    break;
                case '-':
                    temp = a - b;
                    break;
                case '*':
                    temp = a*b;
                    break;
                default:
                    break;
                }
                vector<int> num_copy(num);
                vector<char> ope_copy(ope);
                num_copy[i] = temp;
                num_copy.erase(num_copy.begin() + i + 1);
                ope_copy.erase(ope_copy.begin() + i);
                helper(res, num_copy, ope_copy);
            }
        }
    }
};

另外一种递归方法(去重复):

class Solution {
public:
    vector<int> diffWaysToCompute(string input) {
        unordered_map<string, vector<int>> dpMap;
        return computeWithDP(input, dpMap);
    }

    vector<int> computeWithDP(string input, unordered_map<string, vector<int>> &dpMap) {
        vector<int> result;
        int size = input.size();
        for (int i = 0; i < size; i++) {
            char cur = input[i];
            if (cur == '+' || cur == '-' || cur == '*') {
                // Split input string into two parts and solve them recursively
                vector<int> result1, result2;
                string substr = input.substr(0, i);
                // check if dpMap has the result for substr
                if (dpMap.find(substr) != dpMap.end())
                    result1 = dpMap[substr];//没有重复的
                else
                    result1 = computeWithDP(substr, dpMap);//有重复的,继续递归下去

                substr = input.substr(i + 1);
                if (dpMap.find(substr) != dpMap.end())
                    result2 = dpMap[substr];
                else
                    result2 = computeWithDP(substr, dpMap);

                for (auto n1 : result1) {
                    for (auto n2 : result2) {
                        if (cur == '+')
                            result.push_back(n1 + n2);
                        else if (cur == '-')
                            result.push_back(n1 - n2);
                        else
                            result.push_back(n1 * n2);
                    }
                }
            }
        }
        // if the input string contains only number
        if (result.empty())
            result.push_back(atoi(input.c_str()));
        // save to dpMap
        dpMap[input] = result;
        return result;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值