leetcode 241. Different Ways to Add Parentheses

Posted 巴蜀小小生

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 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"
Output: [0, 2]
Explanation: 
((2-1)-1) = 0 
(2-(1-1)) = 2

Example 2:

Input: "2*3-4*5"
Output: [-34, -14, -10, -10, 10]
Explanation: 
(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

 

长见识了,大概知道分治的用法了, 额,求二叉树的高度的思维和 分治很像啊, 快排应该就是分治算法的典型应用

遍历输入字符串,遇到一个运算符就分别遍历运算符的左边和右边,通过这样的递归就能求到该运算符左边和右边的所有可能的值, 递归的终止情况是,字符串中只有数字;

 1 class Solution {
 2 public:
 3     vector<int> diffWaysToCompute(string input) {
 4         vector<int> ans;
 5         for(int i=0; i<input.size(); i++){
 6             if(input[i]==- || input[i]==+ || input[i]==*){
 7                 vector<int> l=diffWaysToCompute(input.substr(0, i));
 8                 vector<int> r=diffWaysToCompute(input.substr(i+1));
 9                 for(int j=0; j<l.size(); j++){
10                     for(int k=0; k<r.size(); k++){
11                         if(input[i]==-) ans.push_back(l[j]-r[k]);
12                         else if(input[i]==+) ans.push_back(l[j]+r[k]);
13                         else if(input[i]==*) ans.push_back(l[j]*r[k]);
14                     }
15                 }
16             }
17         }
18         if(ans.empty()) ans.push_back(stoi(input));
19         return ans;
20     }
21 };

 

以上是关于leetcode 241. Different Ways to Add Parentheses的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 241. Different Ways to Add Parentheses

leetcode 241. Different Ways to Add Parentheses (Python版)

leetcode 241. Different Ways to Add Parentheses

[LeetCode] 241. Different Ways to Add Parentheses

leetcode [241]Different Ways to Add Parentheses

LeetCode-241 Different Ways to Add Parentheses