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 :
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]
题意:
给一串表达式(由+、-、*以及数字组成),通过加括号改变运算顺序,求所有可能的结果。
思路:
没有想到什么比较巧妙的方法,只能递归所有的可能咯,其中有很多重复计算,等找到好办法了再来更新吧。
C++:
1 class Solution { 2 public: 3 4 //string转为int 5 int getInts(string str) 6 { 7 int ret = 0; 8 9 stringstream ss; 10 ss << str; 11 ss >> ret; 12 13 return ret; 14 } 15 16 vector<int> rec(vector<int>& num, int start, int ends) 17 { 18 vector<int> vec; 19 20 if(start == ends) 21 { 22 vec.push_back(num[start]); 23 return vec; 24 } 25 26 for(int i = start; i <= ends; i++) 27 { 28 if(num[i] == -3) 29 { 30 vector<int> vecl = rec(num, start, i - 1); 31 vector<int> vecr = rec(num, i + 1, ends); 32 33 vector<int>::iterator itl = vecl.begin(); 34 for(; itl != vecl.end(); itl++) 35 { 36 vector<int>::iterator itr = vecr.begin(); 37 for(; itr != vecr.end(); itr++) 38 vec.push_back((*itl) + (*itr)); 39 } 40 } 41 if(num[i] == -1) 42 { 43 vector<int> vecl = rec(num, start, i - 1); 44 vector<int> vecr = rec(num, i + 1, ends); 45 46 vector<int>::iterator itl = vecl.begin(); 47 for(; itl != vecl.end(); itl++) 48 { 49 vector<int>::iterator itr = vecr.begin(); 50 for(; itr != vecr.end(); itr++) 51 vec.push_back((*itl) - (*itr)); 52 } 53 } 54 if(num[i] == -4) 55 { 56 vector<int> vecl = rec(num, start, i - 1); 57 vector<int> vecr = rec(num, i + 1, ends); 58 59 vector<int>::iterator itl = vecl.begin(); 60 for(; itl != vecl.end(); itl++) 61 { 62 vector<int>::iterator itr = vecr.begin(); 63 for(; itr != vecr.end(); itr++) 64 vec.push_back((*itl) * (*itr)); 65 } 66 } 67 } 68 return vec; 69 } 70 71 vector<int> diffWaysToCompute(string input) { 72 73 //先把字符串转换为一个int型的数组,符号用负数来表示 74 vector<int> nums; 75 int index = 0; 76 for(int i = 0; i < input.size(); i++) 77 { 78 if(input[i] == ‘+‘ || input[i] == ‘-‘ || input[i] == ‘*‘) 79 { 80 string str = input.substr(index, i - index); 81 nums.push_back(getInts(str)); 82 nums.push_back(input[i]-46); //加号转换为-3, 减号转换为-1,乘号为-4 83 index = i + 1; 84 } 85 if(i == input.size() - 1) 86 { 87 string str = input.substr(index, input.size() - index); 88 nums.push_back(getInts(str)); 89 } 90 } 91 92 int len = nums.size(); 93 if(len == 0 || len == 1) 94 return nums; 95 96 vector<int> ret = rec(nums, 0, len - 1); 97 return ret; 98 } 99 };
AC: https://leetcode.com/submissions/detail/34357736/
时间: 2024-10-16 04:29:46