[LeetCode] Different Ways to Add Parentheses

本文介绍了一种通过递归分解表达式并计算所有可能结果的方法。该方法将遇到的操作符作为分界点,将输入字符串分为左右两部分,并递归地计算每一部分的所有可能值。

Well, this problem seems to be a little tricky at first glance. However, the idea (taken from this link) is really simple. Let's take the equation 2*3-4*5 in the problem statement as an example to illustrate the idea. 

The idea is fairly simple: each time we encounter an operator, split the input string into two parts, one left to the operator and the other right to it. For example, when we reach -, we split the string into 2*3 and 4*5. Then we recursively (yeah, this is the biggest simplification) compute all possible values of the left and right parts and operate on all the possible pairs of them. The idea will become much more obvious if you read the following code.

 1 class Solution {
 2 public:
 3     vector<int> diffWaysToCompute(string input) {
 4         vector<int> outputs;
 5         int n = input.length();
 6         for (int i = 0; i < n; i++) {
 7             if (input[i] == '+' || input[i] == '-' || input[i] == '*') {
 8                 string left = input.substr(0, i);
 9                 string right = input.substr(i + 1, n - i - 1);
10                 vector<int> lval = diffWaysToCompute(left);
11                 vector<int> rval = diffWaysToCompute(right);
12                 for (int l : lval) {
13                     for (int r : rval) {
14                         switch (input[i]) {
15                             case '+':
16                                 outputs.push_back(l + r);
17                                 break;
18                             case '-':
19                                 outputs.push_back(l - r);
20                                 break;
21                             default:
22                                 outputs.push_back(l * r);
23                         }
24                     }
25                 }
26             }
27         }
28         if (outputs.empty())
29             outputs.push_back(stoi(input));
30         return outputs;
31     }
32 };

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值