Week Training: 241 Different Ways to Add Parentheses

本文介绍了一种使用递归和分治策略解决复杂数学表达式计算问题的方法。通过将原始字符串分解为若干子字符串,并对每个子字符串递归应用相同的过程来计算可能的结果。文章详细解释了如何处理加法、减法和乘法运算符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

As we are learning divide and conquer, a problem like this can help us understand well. It seems hard, since we don't know how long the string is, there might be lots of conditions. However, through the theory of divide and conquer and recursive, we can make the problem concise and easier to deal with. If we meet with operators like '+', '-' and '*', we just divide the string before and after it to 2 substrings, resursively doing the same thing to them. For each 2 substrings, we compute every element of it according to the operator. The principle of this method is easy-understanding, but of course too much loop used causes long run time, which is to be improved.

class Solution {
public:
    vector<int> diffWaysToCompute(string input) {
        vector<int> result;
        for(int i=0;i<input.size();i++){
            char sym = input[i];
            if(sym == '+'||sym == '-'||sym == '*'){
                vector<int> r1 = diffWaysToCompute(input.substr(0,i));
                vector<int> r2 = diffWaysToCompute(input.substr(i+1));
                for(int j=0;j<r1.size();j++){
                    for(int k=0;k<r2.size();k++){
                        if(sym=='+')
                            result.push_back(r1[j]+r2[k]);
                        else if(sym=='-')
                            result.push_back(r1[j]-r2[k]);
                        else if(sym=='*')
                            result.push_back(r1[j]*r2[k]);
                    }
                }
            }
        }
        if(result.empty())
            result.push_back(atoi(input.c_str()));
        return result;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值