算法课第2周第2题——241. Different Ways to Add Parentheses

来源:互联网 发布:julius it 编辑:程序博客网 时间:2024/05/19 14:16

题目描述:

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]



程序代码:

class Solution {public:vector<int> diffWaysToCompute(string input) {// 最终返回的vectorvector<int> res;// 遍历input,若有+ - *,则将该符号前后的部分分治处理for (int i = 0; i < input.size(); i++) {if (input[i] == '+' || input[i] == '-' || input[i] == '*') {string str1 = input.substr(0, i);string str2 = input.substr(i + 1);vector<int> v1 = diffWaysToCompute(str1);vector<int> v2 = diffWaysToCompute(str2);// 二重循环,把符号前后vector中的数做相应运算并存入resfor (int t = 0; t < v1.size(); t++) {for (int j = 0; j < v2.size(); j++) {if (input[i] == '+') {res.push_back(v1[t] + v2[j]);}else if (input[i] == '-') {res.push_back(v1[t] - v2[j]);}else if (input[i] == '*') {res.push_back(v1[t] * v2[j]);}}}}}// 若input中没有+ - *,即input为单个数而没有符号,res此时为emptyif (res.empty()) {int s = atoi(input.c_str());res.push_back(s);}return res;} };


简要题解:

(我在程序代码中也通过注释给出了一些关键部分的思路)

本题主要用到了分治算法。

首先理解题意。需要把一个算式字符串的所有可能结果存入向量中并输出该向量。

接着思考解题的方法。很自然得联想到将+ - *号两侧的算式使用分而治之的方法来进行处理。首先先新建一个向量res用于储存最终的结果。接着遍历input,若出现+ - *符号,则将其前后的部分使用递归的方法进行分治处理,结果分别存在v1和v2两个向量中,再用一个二重循环,将这v1和v2中的所有元素根据+ - *号进行相应的运算,并将运算结果都存入res向量尾部。遍历完input后,若input中没有+ - *(即input为单个数字而没有运算符号),则此时res会为empty(因为在前面的步骤中没有运算结果放入res),那么只要使用atoi函数将input从字符串转为数字并存入res向量尾部即可。

本题是一道比较明显的运用了分治算法的题目。通过本题,我巩固了本周学习的有关分治算法的内容。


0 0