leetcode 241:Different Ways to Add Parentheses
来源:互联网 发布:苹果铃声剪切软件 编辑:程序博客网 时间:2024/05/22 03:31
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 *
.
题目分析:看到这个题,第一反应竟然是相邻数字跟符号的随机组合,然后计算结果后与剩下的再随机组合,这样会导致重复计算,所以结果会重,因为当时想的结果是set,之后想,可以以符号作为区分,符号两边递归计算,并且得到全排列的结果,如果没有符号,直接得到string转num.有点类似于二叉树的求解。
具体代码如下:
public List<Integer> diffWaysToCompute(String input) {int len=input.length();List<Integer> res = new ArrayList<Integer>();if(len<1) return res;for(int i=0;i<len;i++){char c=input.charAt(i);//以符号为分割,计算两边值得全排列if(c=='+'||c=='*'||c=='-'){//递归获得两边的值 List<Integer> left= diffWaysToCompute(input.substring(0,i)); List<Integer> right= diffWaysToCompute(input.substring(i+1)); //全排列得到结果 for(Integer leftnum:left) { for(Integer rightnum:right) { switch(c) { case '+':res.add(leftnum+rightnum); break; case '-':res.add(leftnum-rightnum); break; case '*':res.add(leftnum*rightnum); break; default: break; } } }}}//没有符号分割,直接返回结果if(res.size()==0)res.add(Integer.parseInt(input));return res;}
0 0
- 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
- 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 - Different Ways to Add Parentheses
- [leetCode] Different Ways to Add Parentheses
- Leetcode|Different Ways to Add Parentheses
- 要成为全栈工程师,你需要掌握的
- 【SQL Server 2008】基础知识—数据库登录
- 适配ios6,ios7等注意问题
- 火狐浏览器爆内存溢出
- 理解TCP/IP,SOCKET,HTTP,FTP,RMI,RPC,webservice等的含义和关系
- leetcode 241:Different Ways to Add Parentheses
- Java HashMap工作原理
- 升级Xcode7后所要更改的配置
- 安卓手机型号修改工具(修改软件)使用方法跟步骤
- 快速查找素数 187 (筛选找素数 模板)
- swift 语言编程
- android 支付宝SDK集成
- ssh + Tab 自动补全主机名 别名
- js判断日期大小