241. Different Ways to Add Parentheses

来源:互联网 发布:变老相机软件 编辑:程序博客网 时间:2024/06/08 11:32

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]

分析
这是一道分治的题目,要用分治的思想将问题分解成一个个子问题再做。
这题的思路是,将接收的字符串从左到右进行检测,只要遇到了符号,就将该字符串分为两个部分,递归这个过程。

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <iostream>#include <vector>using namespace std;class Solution {public:    vector<int> diffWaysToCompute(string input) {        vector<int> result;        int len = input.length();        for (int i = 0; i < len; i++) {            char curSym = input[i];            // divide the string into two parts            if (curSym == '+' || curSym == '-' || curSym == '*') {                vector<int> partRes1 = diffWaysToCompute(input.substr(0, i));                // calculate each of the results                for (int index1 = 0; index1 < partRes1.size(); index1++) {                    for (int index2 = 0; index2 < partRes2.size(); index2++) {                        if (curSym == '+')                             result.push_back(partRes1[index1] + partRes2[index2]);                        else if (curSym == '-')                            result.push_back(partRes1[index1] - partRes2[index2]);                        else                            result.push_back(partRes1[index1] * partRes2[index2]);                    }                }            }        }        // if the string has no symbol, store the number        if (result.empty())            result.push_back(atoi(input.c_str()));        return result;    }};// testing the codeint main() {    Solution test;    vector<int> result = test.diffWaysToCompute("2*3-4*5");    for (int i = 0; i < result.size(); i++) {        cout << result[i] << endl;    }    return 0;}
原创粉丝点击