241. Different Ways to Add Parentheses
来源:互联网 发布:变老相机软件 编辑:程序博客网 时间:2024/06/08 11:32
241. 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]
分析
这是一道分治的题目,要用分治的思想将问题分解成一个个子问题再做。
这题的思路是,将接收的字符串从左到右进行检测,只要遇到了符号,就将该字符串分为两个部分,递归这个过程。
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <iostream>#include <vector>using namespace std;class Solution {public: vector<int> diffWaysToCompute(string input) { vector<int> result; int len = input.length(); for (int i = 0; i < len; i++) { char curSym = input[i]; // divide the string into two parts if (curSym == '+' || curSym == '-' || curSym == '*') { vector<int> partRes1 = diffWaysToCompute(input.substr(0, i)); // calculate each of the results for (int index1 = 0; index1 < partRes1.size(); index1++) { for (int index2 = 0; index2 < partRes2.size(); index2++) { if (curSym == '+') result.push_back(partRes1[index1] + partRes2[index2]); else if (curSym == '-') result.push_back(partRes1[index1] - partRes2[index2]); else result.push_back(partRes1[index1] * partRes2[index2]); } } } } // if the string has no symbol, store the number if (result.empty()) result.push_back(atoi(input.c_str())); return result; }};// testing the codeint main() { Solution test; vector<int> result = test.diffWaysToCompute("2*3-4*5"); for (int i = 0; i < result.size(); i++) { cout << result[i] << endl; } return 0;}
阅读全文
0 0
- [leetcode] 241.Different Ways to Add Parentheses
- Leetcode-241.Different Ways to Add Parentheses
- 241. Different Ways to Add Parentheses LeetCode
- Leetcode- 241.Different Ways to Add Parentheses
- [LeetCode]241. Different Ways to Add Parentheses
- 241. Different Ways to Add Parentheses
- [leetcode] 241. Different Ways to Add Parentheses
- 241. Different Ways to Add Parentheses
- 241. Different Ways to Add Parentheses
- LeetCode *** 241. Different Ways to Add Parentheses
- 241. Different Ways to Add Parentheses
- 241. Different Ways to Add Parentheses
- LeetCode 241. Different Ways to Add Parentheses
- 241. Different Ways to Add Parentheses
- 241. Different Ways to Add Parentheses
- LeetCode 241. Different Ways to Add Parentheses
- LeetCode-241.Different Ways to Add Parentheses
- LeetCode 241. Different Ways to Add Parentheses
- 检查IP地址是否输入正确
- ClASSPATH环境变量的配置
- C++ primer 基本语言
- java学习笔记-I/O篇(2):BufferedInputStream
- 解决各种IE兼容问题,IE6,IE7,IE8,IE9,IE10
- 241. Different Ways to Add Parentheses
- html笔记1
- 工具软件 笔记
- ConstraintLayout 完全解析 快来优化你的布局吧
- 在线学习与离线学习
- 关于JS动态修改CSS样式问题(class和style)
- 8.#{}与${}
- jQuery下拉框
- 成员变量,静态变量,与局部变量