zoukankan      html  css  js  c++  java
  • 【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]

    提示:

    这道题我一开始的想法是使用stack,但显然太过复杂。

    其实是可以用递归的方法解决的,即每次遇到一个运算符号,就以该符号为界,将输入字符串拆分成两个子串,作为两个子问题去求解。

    要注意的是需要特殊处理一下输入仅是一个数的情况。另外为了减少重复计算自问题,可以用map保存自问题的结果,加快算法的速度。

    代码:

    class Solution {
    public:
        vector<int> diffWaysToCompute(string input) {
            unordered_map<string, vector<int>> dp;
            return computeSubSeq(dp, input);
        }
        
        vector<int> computeSubSeq(unordered_map<string, vector<int>>& dp, string input) {
            vector<int> res;
            int size = input.length();
            for (int i = 0; i < size; ++i) {
                char c = input[i];
                if (c == '+' || c == '-' || c == '*') {
                    string sub1, sub2;
                    vector<int> res1, res2;
                    // 求位于运算符号前的子串
                    sub1 = input.substr(0, i);
                    if (dp.find(sub1) != dp.end()) {
                        res1 = dp[sub1];
                    } else {
                        res1 = computeSubSeq(dp, sub1);
                    }
                    // 求位于运算符号后的子串
                    sub2 = input.substr(i + 1);
                    if (dp.find(sub2) != dp.end()) {
                        res2 = dp[sub2];
                    } else {
                        res2 = computeSubSeq(dp, sub2);
                    }
                    // 由于子问题会有多种划分方法,所以每一个子算式都会有不同可能的值,我们需要依次遍历求其结果
                    for (int n1 : res1) {
                        for (int n2 : res2) {
                            if (c == '+') {
                                res.push_back(n1 + n2);
                            } else if (c == '-') {
                                res.push_back(n1 - n2);
                            } else {
                                res.push_back(n1 * n2);
                            }
                        }
                    }
                }
            }
            // 处理输入只是单独一个数的情况
            if (res.empty()) {
                res.push_back(atoi(input.c_str()));
            }
            // 将结果保存到map中,以备之后使用
            dp[input] = res;
            return res;
        }
    };
  • 相关阅读:
    this指针是什么?
    C++多态实现原理
    面试题2:实现Singleton模式
    面试题1:赋值运算符函数
    1.Two Sum
    朴素贝叶斯
    K近邻法
    感知机
    数据类型、用户交互、赋值运算
    蓝牙技术概述
  • 原文地址:https://www.cnblogs.com/jdneo/p/5237818.html
Copyright © 2011-2022 走看看