Different Ways to Add Parentheses
Total Accepted: 1708 Total Submissions: 6304My Submissions
Question Solution
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"
.
((2-1)-1) = 0 (2-(1-1)) = 2
Output: [0, 2]
Example 2
Input: "2*3-4*5"
(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
Output: [-34, -14, -10, -10, 10]
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
Hide Tags
Hide Similar Problems
参考了
C++ 4ms Recursive & DP solution with brief explanation - Leetcode Discuss
https://leetcode.com/discuss/48488/c-4ms-recursive-method
这道题目的意思是让你计算出对于一串字符串所有加括号下结果的可能
1. 开始没有明白过来,其实这道题是计算不同加括号下的情况的结果,而最终真的计算时得到的是可以
重复的结果的。
首先是基本的递归的思想,从前往后遍历,对于每一个运算符将其左右子字符串分成两部分,然后计算两边的各种不同的结果来,然后和在一起,这中间不存是不存在加括号的相同发的情况的。
1 #include<iostream> 2 #include<vector> 3 using namespace std; 4 5 vector<int> diffWaysToCompute(string input) { 6 vector<int> result; 7 int len=input.size(); 8 for(int k=0;k<len;k++) 9 { 10 if(input[k]==‘+‘||input[k]==‘-‘||input[k]==‘*‘) 11 { 12 vector<int> result1=diffWaysToCompute(input.substr(0,k)); 13 vector<int> result2=diffWaysToCompute(input.substr(k+1)); 14 for(vector<int>::iterator i=result1.begin();i!=result1.end();i++) 15 for(vector<int>::iterator j=result2.begin();j!=result2.end();j++) 16 { 17 if(input[k]==‘+‘) 18 result.push_back((*i)+(*j)); 19 else if(input[k]==‘-‘) 20 result.push_back((*i)-(*j)); 21 else 22 result.push_back((*i)*(*j)); 23 } 24 } 25 } 26 if(result.empty()) 27 result.push_back(atoi(input.c_str())); 28 return result; 29 } 30 int main() 31 { 32 string input="2*3-4*5"; 33 vector<int> vec; 34 vec=diffWaysToCompute(input); 35 for(int i=0;i<vec.size();i++) 36 cout<<vec[i]<<‘ ‘; 37 cout<<endl; 38 system("pause"); 39 }