码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 241. Different Ways to Add Parentheses

时间:2018-06-24 00:44:23      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:input   public   tin   operator   nbsp   str   情况   push   span   

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

标签:input   public   tin   operator   nbsp   str   情况   push   span   

原文地址:https://www.cnblogs.com/mr-stn/p/9218921.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!