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 *.

Example1:

Input: “2-1-1”
Output: [0, 2]
Explanation:
((2-1)-1) = 0
(2-(1-1)) = 2

分析:

本题属于divide and conquer(分治法)类型,可以根据string中的运算符进行分割,将原string问题划分成两个substring,分别递归计算运算符两端substring所有可能的结果后,再计算整体所有的结果。

拿题中的例子来说,2-1-1,可以分割成2和1-1两个字符串,分别计算两端的结果后再将结果相减。

class Solution {
private:
    string str;
    
public:
    vector<int> diffWaysToCompute(string input) {
        str = input;
        int N = str.length();
        vector<vector<vector<int>>> v(N, vector<vector<int>>(N));
        helpfunc(0, N-1, v);
        return v[0][N-1];
    }
    // calculate all the result of substring from start to end
    // store result in the v[start][end]
    void helpfunc(int start, int end, vector<vector<vector<int>>>& v){
        if(v[start][end].size() != 0) return;
        
        bool has_op = false;
        for(int i = start; i <= end; i++){
            if(is_op(str[i])){
                has_op = true;
                helpfunc(start, i-1, v);
                helpfunc(i+1, end, v);
                for(int j = 0; j < v[start][i-1].size(); j++){
                    for(int k = 0; k < v[i+1][end].size(); k++){
                        v[start][end].emplace_back(do_op(v[start][i-1][j], v[i+1][end][k], str[i]));
                    }
                }
            }
        }
        // when there is no operation char in the string
        // we can directly put it in the vector
        if(!has_op){
            v[start][end].emplace_back(stoi(str.substr(start, end-start+1)));
        }
    }
    
    bool is_op(char c){
        return c == '+' || c == '-' || c == '*';
    }
    
    int do_op(int num1, int num2, char op){
        if(op == '+')
            return num1 + num2;
        if(op == '-')
            return num1 - num2;
        if(op == '*')
            return num1 * num2;
        // should never return -1
        return -1;
    }
};

运行结果

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值