[LeetCode]241. Different Ways to Add Parentheses
2016-03-10 21:25
501 查看
题意: 给你一个字符串,包括数字和运算符(+、-、*)。然后你选择往里面添加括号改变该字符串的运算顺序,求所有可能的运算顺序对应的结果的集合。例如”2-1-1”,可以改为如下形式((2-1)-1) = 0 或者(2-(1-1)) = 2,则结果为[0,2]。
思路: 主要操作就是往里面插入括号,并不涉及移动数字的位置,所以每次找到一个运算符之后,对于两边的字符串求得各自对应的结果集合(递归实现),按照当前对应的运算符规则进行运算,统计结果即可。
代码:
思路: 主要操作就是往里面插入括号,并不涉及移动数字的位置,所以每次找到一个运算符之后,对于两边的字符串求得各自对应的结果集合(递归实现),按照当前对应的运算符规则进行运算,统计结果即可。
代码:
public List<Integer> diffWaysToCompute(String input) { List<Integer> ans = new ArrayList<>(); int len = input.length(); for(int i = 0; i < len; ++i){ if(input.charAt(i) == '+' || input.charAt(i) == '-' || input.charAt(i) == '*'){ List<Integer> left = diffWaysToCompute(input.substring(0, i)); List<Integer> right = diffWaysToCompute(input.substring(i+1)); int len_l = left.size(), len_r = right.size(); for(int l = 0; l < len_l; ++l){ for(int r = 0; r < len_r; ++r){ if(input.charAt(i) == '+'){ ans.add(left.get(l) + right.get(r)); } if(input.charAt(i) == '-'){ ans.add(left.get(l) - right.get(r)); } if(input.charAt(i) == '*'){ ans.add(left.get(l) * right.get(r)); } } } } } if(ans.isEmpty()){ ans.add(Integer.parseInt(input)); } return ans; }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解