zoukankan      html  css  js  c++  java
  • 241. 为运算表达式设计优先级

    给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +, - 以及 * 。

    示例 1:

    输入: "2-1-1"
    输出: [0, 2]
    解释:
    ((2-1)-1) = 0
    (2-(1-1)) = 2
    示例 2:

    输入: "2*3-4*5"
    输出: [-34, -14, -10, -10, 10]
    解释:
    (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

    来源:力扣(LeetCode)

    class Solution {
    public:
        vector<int> diffWaysToCompute(string input) {
            vector<int> res;
            for (int i = 0; i < input.size(); i++) {
                char ch = input[i];
                if (ch == '+' || ch == '-' || ch == '*') {
                    vector<int> a = diffWaysToCompute(input.substr(0, i));
                    vector<int> b = diffWaysToCompute(input.substr(i+1 , input.size()));
                    for (auto i: a) {
                        for (auto j: b) {
                            if (ch == '+')
                                res.push_back(i + j);
                            else if (ch == '-')
                                res.push_back(i - j);
                            else
                                res.push_back(i * j);
                        }
                    }
                }
            }
            if (res.empty())
                res.push_back(atoi(input.c_str()));
         //c_str:Returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.
         //atoi:Convert string to integer
    return res;
        }
    };
  • 相关阅读:
    字节流
    类File
    try...catch语句
    Collections工具类
    类TreeMap
    类HashMap
    类TreeSet
    jquery 选择器加变量
    bootstrap 事件shown.bs.modal用于监听并执行你自己的代码【写hostmanger关联部门遇到的问题及解决方法】
    jquery中append、prepend, before和after方法的区别(一)
  • 原文地址:https://www.cnblogs.com/xxxsans/p/13828870.html
Copyright © 2011-2022 走看看