Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6b23ee0

Browse files
committed
"Different Ways to Add Parentheses"
1 parent 9b86e98 commit 6b23ee0

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

‎README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ The `☢` means that you need to have a LeetCode Premium Subscription.
7575
| 244 | [Shortest Word Distance II]| |
7676
| 243 | [Shortest Word Distance]| |
7777
| 242 | [Valid Anagram] | [C](src/242.c) |
78-
| 241 | [Different Ways to Add Parentheses] | |
78+
| 241 | [Different Ways to Add Parentheses] | [C++](src/241.cpp) |
7979
| 240 | [Search a 2D Matrix II] | [C](src/240.c) |
8080
| 239 | [Sliding Window Maximum] | |
8181
| 238 | [Product of Array Except Self] | [C](src/238.c) |

‎src/241.cpp

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#include <iostream>
2+
#include <vector>
3+
4+
using namespace std;
5+
6+
class Solution {
7+
public:
8+
vector<int> diffWaysToCompute(string input) {
9+
vector<int> result;
10+
for (int k = 0; k < input.length(); k++) {
11+
if (input[k] == '*' || input[k] == '-' || input[k] == '+') {
12+
vector<int> a = diffWaysToCompute(input.substr(0, k));
13+
vector<int> b = diffWaysToCompute(input.substr(k + 1));
14+
for (int i = 0; i < a.size(); i++) {
15+
for (int j = 0; j < b.size(); j++) {
16+
if (input[k] == '+') {
17+
result.push_back(a[i] + b[j]);
18+
}
19+
else if (input[k] == '-') {
20+
result.push_back(a[i] - b[j]);
21+
}
22+
else {
23+
result.push_back(a[i] * b[j]);
24+
}
25+
}
26+
}
27+
28+
}
29+
}
30+
if (result.size() == 0) {
31+
result.push_back(stoi(input));
32+
}
33+
return result;
34+
}
35+
};
36+
37+
int main() {
38+
39+
Solution s;
40+
vector<int> ans = s.diffWaysToCompute("2*3-4*5");
41+
42+
for (int i = 0; i < ans.size(); i++) {
43+
printf("%d ", ans[i]);
44+
}
45+
printf("\n");
46+
47+
return 0;
48+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /