Week Training: 241 Different Ways to Add Parentheses
来源:互联网 发布:幼儿园淘宝活动方案 编辑:程序博客网 时间:2024/06/05 21:00
As we are learning divide and conquer, a problem like this can help us understand well. It seems hard, since we don't know how long the string is, there might be lots of conditions. However, through the theory of divide and conquer and recursive, we can make the problem concise and easier to deal with. If we meet with operators like '+', '-' and '*', we just divide the string before and after it to 2 substrings, resursively doing the same thing to them. For each 2 substrings, we compute every element of it according to the operator. The principle of this method is easy-understanding, but of course too much loop used causes long run time, which is to be improved.
class Solution {public: vector<int> diffWaysToCompute(string input) { vector<int> result; for(int i=0;i<input.size();i++){ char sym = input[i]; if(sym == '+'||sym == '-'||sym == '*'){ vector<int> r1 = diffWaysToCompute(input.substr(0,i)); vector<int> r2 = diffWaysToCompute(input.substr(i+1)); for(int j=0;j<r1.size();j++){ for(int k=0;k<r2.size();k++){ if(sym=='+') result.push_back(r1[j]+r2[k]); else if(sym=='-') result.push_back(r1[j]-r2[k]); else if(sym=='*') result.push_back(r1[j]*r2[k]); } } } } if(result.empty()) result.push_back(atoi(input.c_str())); return result; }};
0 0
- Week Training: 241 Different Ways to Add Parentheses
- 241. Different Ways to Add Parentheses(week 2)
- leetcode 241 Different Ways to Add Parentheses
- 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
- LeetCode(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
- 【LEETCODE】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
- Leetcode #241 Different Ways to Add Parentheses
- 241 Different Ways to Add Parentheses
- LeetCode #241: Different Ways to Add Parentheses
- 167. Two Sum II
- 计算器布局
- Activity的生命周期
- 马哥2016linux就业班+架构班+运维班全套
- stm32常用数据类型 U8、U16、U32到底代表什么?
- Week Training: 241 Different Ways to Add Parentheses
- 好玩的单片机——数码管原理(一)
- 【codeforces 777E】Hanoi Factory【动态规划+线段树】
- AndroidStudio工程导入错误
- 查找算法
- 广度优先搜索BFS之二叉树的构造及遍历
- java在main里面调用方法
- 前端服务化——页面搭建工具的死与生
- Java统计单词频率