Different Ways to Add Parentheses

原题: https://leetcode.com/problems/different-ways-to-add-parentheses/description/

题意: 给定一个包含数字和运算符的字符串,返回所有对数字与运算符分组可能得到的计算结果。有效的运算符为 +, - 和 *。

例子: 

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]

标签: parentheses、运算符、ways、output、add、面试
猜你感兴趣的圈子:
LeetCode交流圈
  • Bingo
    2017-08-18 17:56:25 1楼#1层
    Python解法一:
    class Solution(object):
        def diffWaysToCompute(self, input):
            """
            :type input: str
            :rtype: List[int]
            """
            if input.isdigit(): return [int(input)]
            result = []
            for i, c in enumerate(input):
                if c in '+-*':
                    left = self.diffWaysToCompute(input[:i])
                    right = self.diffWaysToCompute(input[i+1:])
                    for l in left:
                        for r in right:
                            result.append(eval(str(l) + c + str(r)))
            return result
  • Bingo
    2017-08-18 17:57:14 2楼#1层
    Python解法二:
    class Solution:
        # @param {string} input
        # @return {integer[]}
        def diffWaysToCompute(self, input):
            exprDict = dict()
            def dfs(nums, ops):
                if ops:
                    for x in range(len(ops)):
                        dfs(nums[:x]+['('+nums[x]+ops[x]+nums[x+1]+')']+nums[x+2:],ops[:x]+ops[x+1:])
                elif nums[0] not in exprDict:
                    exprDict[nums[0]] = eval(nums[0])
            nums, ops = [], []
            input = re.split(r'(\D)', input)
            for x in input:
                if x.isdigit():
                    nums.append(x)
                else:
                    ops.append(x)
            dfs(nums, ops)
            return exprDict.values()
  • Bingo
    2017-08-18 17:57:50 3楼#1层
    Python解法三:
    class Solution:
        # @param {string} input
        # @return {integer[]}
        def diffWaysToCompute(self, input):
            return [eval(`a`+c+`b`)
                for i, c in enumerate(input) if c in '+-*'
                for a in self.diffWaysToCompute(input[:i])
                for b in self.diffWaysToCompute(input[i+1:])] or [int(input)]
  • Bingo
    2017-08-18 17:58:18 4楼#1层
    Python解法四:
    class Solution:
        # @param {string} input
        # @return {integer[]}
        def diffWaysToCompute(self, input):
            return [a+b if c == '+' else a-b if c == '-' else a*b
                for i, c in enumerate(input) if c in '+-*'
                for a in self.diffWaysToCompute(input[:i])
                for b in self.diffWaysToCompute(input[i+1:])] or [int(input)]
  • Bingo
    2017-08-18 17:59:39 5楼#1层
    C++解法一:
    class Solution {
    public:
        vector<int> diffWaysToCompute(string input) {
            vector<int> result;
            int size = input.size();
            for (int i = 0; i < size; i++) {
                char cur = input[i];
                if (cur == '+' || cur == '-' || cur == '*') {
                    // Split input string into two parts and solve them recursively
                    vector<int> result1 = diffWaysToCompute(input.substr(0, i));
                    vector<int> result2 = diffWaysToCompute(input.substr(i+1));
                    for (auto n1 : result1) {
                        for (auto n2 : result2) {
                            if (cur == '+')
                                result.push_back(n1 + n2);
                            else if (cur == '-')
                                result.push_back(n1 - n2);
                            else
                                result.push_back(n1 * n2);    
                        }
                    }
                }
            }
            // if the input string contains only number
            if (result.empty())
                result.push_back(atoi(input.c_str()));
            return result;
        }
    };
  • Bingo
    2017-08-18 18:03:01 6楼#1层
    C++解法二:
    class Solution {
    public:
    	vector<int> diffWaysToCompute(string input) {
    		unordered_map<string, vector<int>> dpMap;
    		return computeWithDP(input, dpMap);
    	}
    
    	vector<int> computeWithDP(string input, unordered_map<string, vector<int>> &dpMap) {
    		vector<int> result;
    		int size = input.size();
    		for (int i = 0; i < size; i++) {
    			char cur = input[i];
    			if (cur == '+' || cur == '-' || cur == '*') {
    				// Split input string into two parts and solve them recursively
    				vector<int> result1, result2;
    				string substr = input.substr(0, i);
    				// check if dpMap has the result for substr
    				if (dpMap.find(substr) != dpMap.end())
    					result1 = dpMap[substr];
    				else
    					result1 = computeWithDP(substr, dpMap);
    
    				substr = input.substr(i + 1);
    				if (dpMap.find(substr) != dpMap.end())
    					result2 = dpMap[substr];
    				else
    					result2 = computeWithDP(substr, dpMap);
    				
    				for (auto n1 : result1) {
    					for (auto n2 : result2) {
    						if (cur == '+')
    							result.push_back(n1 + n2);
    						else if (cur == '-')
    							result.push_back(n1 - n2);
    						else
    							result.push_back(n1 * n2);
    					}
    				}
    			}
    		}
    		// if the input string contains only number
    		if (result.empty())
    			result.push_back(atoi(input.c_str()));
    		// save to dpMap
    		dpMap[input] = result;
    		return result;
    	}
    };
  • Bingo
    2017-08-18 18:03:43 7楼#1层
    Java:
    public class Solution {
        public List<Integer> diffWaysToCompute(String input) {
            List<Integer> ret = new LinkedList<Integer>();
            for (int i=0; i<input.length(); i++) {
                if (input.charAt(i) == '-' ||
                    input.charAt(i) == '*' ||
                    input.charAt(i) == '+' ) {
                    String part1 = input.substring(0, i);
                    String part2 = input.substring(i+1);
                    List<Integer> part1Ret = diffWaysToCompute(part1);
                    List<Integer> part2Ret = diffWaysToCompute(part2);
                    for (Integer p1 :   part1Ret) {
                        for (Integer p2 :   part2Ret) {
                            int c = 0;
                            switch (input.charAt(i)) {
                                case '+': c = p1+p2;
                                    break;
                                case '-': c = p1-p2;
                                    break;
                                case '*': c = p1*p2;
                                    break;
                            }
                            ret.add(c);
                        }
                    }
                }
            }
            if (ret.size() == 0) {
                ret.add(Integer.valueOf(input));
            }
            return ret;
        }
    }
  • 回复
隐藏