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]

思路

左右子串分别计算所有可能, 然后全排列.
类似数的计数问题(具有n个节点的不同形态的树有多少棵?)
可以参考Unique Binary Search Trees II
(http://www.cnblogs.com/ganganloveu/p/4138344.html)

code

class Solution {
public:
    bool isOp(const char op) {
       return op == '+' || op == '*' || op == '-';
    }

    int Ops(const int a, const int b, const char op) {
      if(op == '+') {
          return a + b;
      } else if(op == '-') {
          return a - b;
      } else if(op == '*') {
          return a * b;
      }
    }

    vector<int> diffWaysToCompute(string input) {
        vector<int> res;
        int len = input.length();
        for(int i = 0; i < len; i++) {
            if(isOp(input[i])) {
                vector<int> left = diffWaysToCompute(input.substr(0, i));
                vector<int> right = diffWaysToCompute(input.substr(i + 1));
                for(int l = 0; l < left.size(); l++) {
                    for(int r = 0; r < right.size(); r++) {
                        res.push_back(Ops(left[l], right[r], input[i]));
                    }
                }
            }
        }
        if(res.empty()) {
            res.push_back(atoi(input.c_str()));
        }
        return res;
    }
};

你可能感兴趣的:(Different Ways to Add Parentheses)