您的位置:首页 > Web前端

241. Different Ways to Add Parentheses

2015-11-30 07:14 316 查看
题目:

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]


链接: http://leetcode.com/problems/different-ways-to-add-parentheses/

题解:

这题说是Different Ways to add parentheses,其实意思就是忽略运算符的优先级来计算算式。对此我们的解法是: 在算式valid的条件下,只要遇到运算符,我们就计算出左侧的数和右侧的数,然后根据这个运算符来得到结果。看discuss的时候发现Stefan Pochmann大神的解法...一行,擦,这哥们魔方还玩得很好,据说得过德国魔方比赛第一,是真牛。

Time Complexity - O(3n), Space Complexity - O(3n)

public class Solution {
public List<Integer> diffWaysToCompute(String input) {
if(input == null || input.length() == 0)
return new ArrayList<Integer>();
List<Integer> res = new ArrayList<>();

for(int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if(c == '+' || c == '*' || c == '-') {
List<Integer> l1 = diffWaysToCompute(input.substring(0, i));
List<Integer> l2 = diffWaysToCompute(input.substring(i + 1));
for( int x : l1) {
for(int y : l2) {
if(c == '+')
res.add(x + y);
else if(c == '-')
res.add(x - y);
else
res.add(x * y);
}
}
}
}

if(res.size() == 0)
res.add(Integer.valueOf(input));
return res;
}
}


Reference:
https://leetcode.com/discuss/48468/1-11-lines-python-9-lines-c https://leetcode.com/discuss/60626/share-a-clean-and-short-java-solution https://leetcode.com/discuss/53566/python-easy-to-understand-solution-divide-and-conquer https://leetcode.com/discuss/61840/java-recursive-9ms-and-dp-4ms-solution https://leetcode.com/discuss/48477/a-recursive-java-solution-284-ms https://leetcode.com/discuss/48488/c-4ms-recursive-%26-dp-solution-with-brief-explanation https://leetcode.com/discuss/48494/what-is-the-time-complexity-of-divide-and-conquer-method https://leetcode.com/discuss/55255/clean-ac-c-solution-with-explanation
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: