LeetCode 241. Different Ways to Add Parenthess 解题报告

来源:互联网 发布:单片机51交通灯程序 编辑:程序博客网 时间:2024/05/27 14:12

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

((2-1)-1) = 0
(2-(1-1)) = 2

Output: [0, 2]

Example2 :
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]


注意事项

没有。


解题思路

我的思路:

这道题使用分治策略进行解题。很关键的一点,每一个运算符都可以成为最后执行的那一个运算符,因此,以运算符为界,把字符串分为左右两个子字符串,分别求子字符串可能的结果,再将左右对应结果相乘,因为求子字符串的结果,与求原始字符串的结果是同样的问题,所以子字符串可以按同样的方式的分解,最后分解的边界是只有单个数字字符。
所以只要遍历一次字符串,分别以各个运算符为最后一个执行的运算符,算出可能的结果,最后返回所有计算出的结果就行。
需要注意的是字符串可能不包含运算符,这种情况相当于分解的边界情况。


代码

我的代码

class Solution {public:    vector<int> diffWaysToCompute(string input) {        vector<int> result;        for (int i = 0; i < input.size(); i++) {            if (!isdigit(input[i])) {                vector<int> left = diffWaysToCompute(input.substr(0, i));                vector<int> right = diffWaysToCompute(input.substr(i + 1));                for (int l: left) {                    for (int r: right) {                        if (input[i] == '+') result.push_back(l + r);                        if (input[i] == '-') result.push_back(l - r);                        if (input[i] == '*') result.push_back(l * r);                    }                }            }        }        if (result.empty())             result.push_back(atoi(input.c_str()));        return result;    }};

总结

这道题是使用分治策略,关键的一点是懂得怎么将原始问题分解为同样类型的子问题,因为原始问题是求字符串所有可能的运算顺序的结果,因此对问题进行分解的方向就是将原始字符串分为更小的子字符串,同时计算出分解的子字符串的结果能够用于求原始字符串的结果,结合每个运算符都会成为一次最后执行的运算符这一点就能得知分解的方式是以运算符为界进行划分。
通过这道题,我复习了一遍分治的思想,应用分治最重要的是选择正确地分解方式,并且知道分解的边界是什么。这是本周完成的第三道题,下周继续,加油~

0 0
原创粉丝点击