leetcode@ [241] Different Ways to Add Parentheses (Divide and Conquer)
https://leetcode.com/problems/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"
.
((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]
为数不多的考察分治算法的题:
class Solution { public: bool isNumber(string s) { for(int i=0; i<s.length(); ++i) { if(!(s[i] <= '9' && s[i] >= '0')) return false; } return true; } int toInt(string s) { if(s == "0") return 0; int res = 0; for(int i=0; i<s.length(); ++i) { res = res*10 + (s[i]-'0'); } return res; } vector<int> dfs(string input) { vector<int> load; if(isNumber(input)) { load.push_back(toInt(input)); return load; } int len = input.length(); vector<int> l, r; for(int i=0; i<len; ++i) { if(input[i] == '-') { l = dfs(input.substr(0, i)); r = dfs(input.substr(i+1, len-i-1)); for(int p=0; p<l.size(); ++p) { for(int q=0; q<r.size(); ++q) { load.push_back(l[p] - r[q]); } } } else if(input[i] == '+') { l = dfs(input.substr(0, i)); r = dfs(input.substr(i+1, len-i-1)); for(int p=0; p<l.size(); ++p) { for(int q=0; q<r.size(); ++q) { load.push_back(l[p] + r[q]); } } } else if(input[i] == '*') { l = dfs(input.substr(0, i)); r = dfs(input.substr(i+1, len-i-1)); for(int p=0; p<l.size(); ++p) { for(int q=0; q<r.size(); ++q) { load.push_back(l[p] * r[q]); } } } } return load; } vector<int> diffWaysToCompute(string input) { vector<int> res; int len = input.length(); if(len == 0) return res; if(isNumber(input)) { res.push_back(toInt(input)); return res; } vector<int> l, r; for(int i=0; i<len; ++i) { if(input[i] == '-') { l = dfs(input.substr(0, i)); r = dfs(input.substr(i+1, len-i-1)); for(int p=0; p<l.size(); ++p) { for(int q=0; q<r.size(); ++q) { res.push_back(l[p] - r[q]); } } } else if(input[i] == '+') { l = dfs(input.substr(0, i)); r = dfs(input.substr(i+1, len-i-1)); for(int p=0; p<l.size(); ++p) { for(int q=0; q<r.size(); ++q) { res.push_back(l[p] + r[q]); } } } else if(input[i] == '*') { l = dfs(input.substr(0, i)); r = dfs(input.substr(i+1, len-i-1)); for(int p=0; p<l.size(); ++p) { for(int q=0; q<r.size(); ++q) { res.push_back(l[p] * r[q]); } } } } //sort(res.begin(), res.end()); return res; } };