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]

Credits:

Special thanks to @mithmatt for adding this problem and creating all test cases.

因爲需要用到 vector,所以選用了c++,代碼如下:

#include <iostream>
#include <vector>
#include <string>
#include <stdlib.h>

using namespace std;


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

int main() {

        string input;
        cin >> input;
        Solution s;
        vector<int> r = s.diffWaysToCompute(input);
        for(vector<int>::iterator iter = r.begin(); iter != r.end(); ++iter) {
                cout << *iter << endl;
        }
        return 0;
}

暫時想到這,過第二遍的時候有好的算法再改進。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章