【LeetCode】241. Different Ways to Add Parentheses
LeetCode to add different Ways Parentheses
2023-09-11 14:20:27 时间
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]
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
与Unique Binary Search Trees II思路类似,可以对照看。
本题参考Gcdofree的做法
左右子串分别计算所有可能,然后全排列。
class Solution { public: vector<int> diffWaysToCompute(string input) { vector<int> ret; for(int i = 0; i < input.size(); i ++) { if(input[i] == '+' || input[i] == '-' || input[i] == '*') { vector<int> left = diffWaysToCompute(input.substr(0, i)); vector<int> right = diffWaysToCompute(input.substr(i+1)); for(int j = 0; j < left.size(); j ++) { for(int k = 0; k < right.size(); k ++) { if(input[i] == '+') ret.push_back(left[j] + right[k]); else if(input[i] == '-') ret.push_back(left[j] - right[k]); else ret.push_back(left[j] * right[k]); } } } } if(ret.empty()) ret.push_back(atoi(input.c_str())); return ret; } };
相关文章
- Leetcode——1. 两数之和
- Java实现 LeetCode 592 分数加减运算(纯体力活)
- Java实现 LeetCode 438 找到字符串中所有字母异位词
- Java实现 LeetCode 403 青蛙过河
- Java实现 LeetCode 355 设计推特
- Java实现 LeetCode 330 按要求补齐数组
- Java实现 LeetCode 143 重排链表
- Java实现 LeetCode 125 验证回文串
- Java实现 LeetCode 13 罗马数字转整数
- 【LeetCode算法-13】Roman to Integer
- (LeetCode 41)First Missing Positive
- [LeetCode] First Bad Version
- [LeetCode] Best Time to Buy and Sell Stock II
- [LeetCode] Best Time to Buy and Sell Stock
- LeetCode-769. 最多能完成排序的块【贪心,一次遍历,单调栈,排序】
- Leetcode学习计划之动态规划入门day21(377,343,279)
- LeetCode【8】. String to Integer (atoi) --java实现
- Find Minimum in Rotated Sorted Array 旋转数组中找最小值 @LeetCode
- [LeetCode] 108. Convert Sorted Array to Binary Search Tree ☆(升序数组转换成一个平衡二叉树)
- leetcode dfs Validate Binary Search Tree
- leetcode dfs Flatten Binary Tree to Linked List
- leetcode 108. Convert Sorted Array to Binary Search Tree
- leetcode 13. Roman to Integer
- leetcode 538. Convert BST to Greater Tree