1. 程式人生 > >leetcode 241. Different Ways to Add Parentheses

leetcode 241. Different Ways to Add Parentheses

str ive esc ati 一個 etc 所有 cto add

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