LN : leetcode 241 Different Ways to Add Parentheses

时间:2024-10-30 20:05:20

lc 241 Different Ways to Add Parentheses


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]

分治法 Accepted##

这几周的算法课,老师一直在讲分治法的应用,所以现在尝试利用分治法去解决这个问题。利用递归,将复杂的问题拆分成同样的小的问题。

分治法的精髓:

分--将问题分解为规模更小的子问题;

治--将这些规模更小的子问题逐个击破;

合--将已解决的子问题合并,最终得出“母”问题的解;

class Solution {
public:
vector<int> diffWaysToCompute(string input) {
vector<int> ans;
for (int i = 0; i < input.size(); i++) {
char c = input[i];
if (ispunct(c)) {
for (auto a : diffWaysToCompute(input.substr(0, i))) {
for (auto b : diffWaysToCompute(input.substr(i+1))) {
ans.push_back(c == '-' ? a-b : c == '+' ? a+b : a*b);
}
}
}
}
return ans.size() ? ans : vector<int>{stoi(input)};
}
};