贪心类型
贪心算法(又称贪婪算法)是指,在对问题求解时,总是做出在当前看来是最好的选择。也就是说,不从整体最优上加以考虑,算法得到的是在某种意义上的局部最优解 。 贪心算法不是对所有问题都能得到整体最优解,关键是贪心策略的选择。也就是说,不从整体最优上加以考虑,做出的只是在某种意义上的局部最优解 。
局部最优得出整体最优
相关题目 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 class Solution { public boolean lemonadeChange (int [] bills) { int five = 0 , ten = 0 ; for (int bill : bills) { if (bill == 5 ) { five++; } else if (bill == 10 ) { if (five == 0 ) { return false ; } five--; ten++; } else { if (five > 0 && ten > 0 ) { five--; ten--; } else if (five >= 3 ) { five -= 3 ; } else { return false ; } } } return true ; } }
广度优先遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 class Solution { int [][] visit ; char [][] arr; public int numIslands (char [][] grid) { int ans = 0 ; arr = grid; visit = new int [grid.length][grid[0 ].length]; for (int i=0 ;i<grid.length;i++){ for (int j = 0 ; j < grid[i].length; j++) { if (grid[i][j]=='1' &&visit[i][j]==0 ){ bfs(i,j); ans+=1 ; } } } return ans; } public void bfs (int x,int y) { visit[x][y]=1 ; if (x-1 >=0 &&visit[x-1 ][y]==0 &&arr[x-1 ][y]=='1' )bfs(x-1 ,y); if (x+1 <arr.length&&visit[x+1 ][y]==0 &&arr[x+1 ][y]=='1' )bfs(x+1 ,y); if (y-1 >=0 &&visit[x][y-1 ]==0 &&arr[x][y-1 ]=='1' )bfs(x,y-1 ); if (y+1 <arr[x].length&&visit[x][y+1 ]==0 &&arr[x][y+1 ]=='1' )bfs(x,y+1 ); } }
贪心算法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 class Solution { public int maxProfit (int [] prices) { int len = prices.length; if (len < 2 )return 0 ; int [] cash = new int [len]; int [] hold = new int [len]; cash[0 ] = 0 ; hold[0 ] = -prices[0 ]; for (int i = 1 ; i < len; i++) { cash[i] = Math.max(cash[i - 1 ], hold[i - 1 ] + prices[i]); hold[i] = Math.max(hold[i - 1 ], cash[i - 1 ] - prices[i]); } return cash[len - 1 ]; } public int maxProfit (int [] prices) { int len = prices.length; if (len < 2 )return 0 ; int cash = 0 ; int hold = -prices[0 ]; int preCash = cash; int preHold = hold; for (int i = 1 ; i < len; i++) { cash = Math.max(preCash, preHold + prices[i]); hold = Math.max(preHold, preCash - prices[i]); preCash = cash; preHold = hold; } return cash; } public int maxProfit (int [] prices) { int ans = 0 ; int n = prices.length; for (int i = 1 ; i < n; ++i) { ans += Math.max(0 , prices[i] - prices[i - 1 ]); } return ans; } }
给定一个非负整数数组,你最初位于数组的第一个位置。数组中的每个元素代表你在该位置可以跳跃的最大长度。判断你是否能够到达最后一个位置。
1 2 3 输入: [2,3,1,1,4] 输出: true 解释: 我们可以先跳 1 步,从位置 0 到达 位置 1, 然后再从位置 1 跳 3 步到达最后一个位置。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 public class Solution { public boolean canJump (int [] nums) { int n = nums.length; int rightmost = 0 ; for (int i = 0 ; i < n; ++i) { if (i <= rightmost) { rightmost = Math.max(rightmost, i + nums[i]); if (rightmost >= n - 1 ) { return true ; } } } return false ; } public boolean canJump0 (int [] nums) { return bfs(0 ,nums); } public boolean bfs (int index,int [] nums) { if (index==nums.length-1 )return true ; for (int j = 1 ; j < nums[index]; j++) { boolean bfs = bfs(index + j, nums); if (bfs)return true ; } return false ; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 class Solution { public int jump (int [] nums) { int position = nums.length - 1 ; int steps = 0 ; while (position > 0 ) { for (int i = 0 ; i < position; i++) { if (i + nums[i] >= position) { position = i; steps++; break ; } } } return steps; } public int jump (int [] nums) { int end = 0 ; int maxPosition = 0 ; int steps = 0 ; for (int i = 0 ; i < nums.length - 1 ; i++) { maxPosition = Math.max(maxPosition, i + nums[i]); if (i == end) { end = maxPosition; steps++; } } return steps; } public int jump (int [] nums) { int length = nums.length; int dp[] = new int [length]; dp[0 ] = 0 ; if (length==1 )return 0 ; int maxn = 0 ; for (int i=0 ;i<=maxn;i++) { maxn = Math.max(maxn, i+nums[i]); if (maxn>=length-1 ) { dp[length-1 ]=dp[length-1 ]==0 ?dp[i]+1 :Math.min(dp[length-1 ], dp[i]+1 ); return dp[length-1 ]; } for (int j=i+1 ;j<=i+nums[i]&&j<length;j++) { dp[j]=dp[j]==0 ?dp[i]+1 :Math.min(dp[j], dp[i]+1 ); } } return dp[nums.length-1 ]; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 class Solution { public int maxSubarraySumCircular (int [] A) { int [] dp = new int [A.length]; dp[0 ] = A[0 ]; int max = dp[0 ]; int sum = dp[0 ]; for (int i = 1 ; i < dp.length; i++) { sum += A[i]; dp[i] = A[i] + Math.max(dp[i - 1 ], 0 ); max = Math.max(dp[i], max); } int min = 0 ; for (int i = 1 ; i < dp.length - 1 ; i++) { dp[i] = A[i] + Math.min(0 , dp[i - 1 ]); min = Math.min(dp[i], min); } return Math.max(sum - min, max); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 class Solution { public int maxProduct0 (int [] nums) { int maxF = nums[0 ], minF = nums[0 ], ans = nums[0 ]; int length = nums.length; for (int i = 1 ; i < length; ++i) { int mx = maxF, mn = minF; maxF = Math.max(mx * nums[i], Math.max(nums[i], mn * nums[i])); minF = Math.min(mn * nums[i], Math.min(nums[i], mx * nums[i])); ans = Math.max(maxF, ans); } return ans; } public int maxProduct (int [] nums) { int n = nums.length; if (n == 1 ) return nums[0 ]; int max = Integer.MIN_VALUE; int muti = 1 ; int l = 0 , r = 0 ; while (r <= n && l < n){ if (r == n){ muti /= nums[l++]; }else { if (nums[r] != 0 ){ muti *= nums[r++]; }else if (l < r){ muti /= nums[l++]; }else { max = Math.max(max, 0 ); ++l; ++r; } } if (l != r) max = Math.max(max, muti); } return max; } }
给你一个整数数组 nums ,请你求出乘积为正数的最长子数组的长度。 一个数组的子数组是由原数组中零个或者更多个连续数字组成的数组。 请你返回乘积为正数的最长子数组长度。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 class Solution { public int getMaxLen (int [] nums) { int length = nums.length; int [] positive = new int [length]; int [] negative = new int [length]; if (nums[0 ] > 0 ) { positive[0 ] = 1 ; } else if (nums[0 ] < 0 ) { negative[0 ] = 1 ; } int maxLength = positive[0 ]; for (int i = 1 ; i < length; i++) { if (nums[i] > 0 ) { positive[i] = positive[i - 1 ] + 1 ; negative[i] = negative[i - 1 ] > 0 ? negative[i - 1 ] + 1 : 0 ; } else if (nums[i] < 0 ) { positive[i] = negative[i - 1 ] > 0 ? negative[i - 1 ] + 1 : 0 ; negative[i] = positive[i - 1 ] + 1 ; } else { positive[i] = 0 ; negative[i] = 0 ; } maxLength = Math.max(maxLength, positive[i]); } return maxLength; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class Solution { / / 思路:双指针从头尾缩小 public int maxArea(int [] height) { int m = height.length; if(m< 2 )return 0 ; int left = 0 ,right = m-1 ; int ans = 0 ; while(left < right ){ ans = Math.max (Math.min (height[left ],height[right ])* (right - left ),ans); if(height[left ]<= height[right ])left + + ; else right } return ans; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 class Solution { / / 思路:排序+ 贪心 / / 优先贪心选择第一个字符小的 / / x+ y < y+ x public String minNumber(int [] nums) { int n = nums.length; String[] strs = new String[n]; for (int i= 0 ;i< n;i+ + )strs[i] = String.valueOf(nums[i]); Arrays.sort(strs,(x,y)- > (x+ y).compareTo(y+ x)); StringBuilder sb = new StringBuilder(); for (int i= 0 ;i< n;i+ + )sb.append(strs[i]); return sb.toString(); } }
135. 分发糖果 (hard) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 class Solution { / / 1. 每个孩子至少分配到 1 个糖果。 / / 2. 相邻两个孩子评分更高的孩子会获得更多的糖果。 / / 思路:贪心 / / 先对每一个元素设置为1 ,满足条件1 / / 从左边遍历:如果ratings[i]> ratings[i-1 ]那说明,i分到的糖果多于i-1 ,即ratings[i]= ratings[i-1 ]+ 1 / / 从右边遍历:如果ratings[i]> ratings[i+ 1 ]那说明,i分到的糖果多于i+ 1 ,即ratings[i]= ratings[i+ 1 ]+ 1 / / 贪心取两者最大值即为答案 public int candy(int [] ratings) { int [] left = new int [ratings.length]; int [] right = new int [ratings.length]; Arrays.fill(left , 1 ); Arrays.fill(right , 1 ); for (int i = 1 ; i < ratings.length; i+ + ) if(ratings[i] > ratings[i - 1 ]) left [i] = left [i - 1 ] + 1 ; int count = left [ratings.length - 1 ]; for (int i = ratings.length - 2 ; i >= 0 ; i if(ratings[i] > ratings[i + 1 ]) right [i] = right [i + 1 ] + 1 ; count + = Math.max (left [i], right [i]); } return count; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 class Solution { / / 贪心:前面查找最小的与后面最大的交换 public int maximumSwap(int num) { StringBuilder sb = new StringBuilder(String.valueOf(num)); int n = sb.length(); for (int i= 0 ;i< n;i+ + ){ char change = sb.charAt(i); for (int j= i+ 1 ;j< n;j+ + ){ if(change< sb.charAt(j)){/ / 从[j- ,n-1 ]查找出最大的一个来交换 int maxIndex = j; for (int k= maxIndex+ 1 ;k< n;k+ + )maxIndex= sb.charAt(maxIndex)<= sb.charAt(k)?k:maxIndex; char max = sb.charAt(maxIndex); sb.setCharAt(i,max); sb.setCharAt(maxIndex,change); int x = 0 ; for (int index= 0 ;index< n;index+ + )x= x* 10 + sb.charAt(index)- '0' ; return x; } } } return num; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 class Solution { public List<Integer> pancakeSort (int [] arr) { List<Integer> ret = new ArrayList <Integer>(); for (int n = arr.length; n > 1 ; n--) { int index = 0 ; for (int i = 1 ; i < n; i++) { if (arr[i] >= arr[index]) { index = i; } } if (index == n - 1 ) { continue ; } reverse(arr, index); reverse(arr, n - 1 ); ret.add(index + 1 ); ret.add(n); } return ret; } public void reverse (int [] arr, int end) { for (int i = 0 , j = end; i < j; i++, j--) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 class Solution { public int canCompleteCircuit (int [] gas, int [] cost) { int n = gas.length; int retIndex = 0 ; int reduce = 0 ; int up = 0 ; for (int i=0 ;i<n;i++){ reduce += gas[i] - cost[i]; up += gas[i] - cost[i]; if (up<0 ){ retIndex = i+1 ; up = 0 ; } } return reduce>=0 ?retIndex:-1 ; } public int canCompleteCircuit (int [] gas, int [] cost) { int n = gas.length; int i = 0 ; while (i < n) { int sumOfGas = 0 , sumOfCost = 0 ; int cnt = 0 ; while (cnt < n) { int j = (i + cnt) % n; sumOfGas += gas[j]; sumOfCost += cost[j]; if (sumOfCost > sumOfGas) { break ; } cnt++; } if (cnt == n) { return i; } else { i = i + cnt + 1 ; } } return -1 ; } }
1 2 3 4 5 6 7 8 9 10 11 12 class Solution { public int maxProfit (int [] prices) { int ret = 0 ; int n = prices.length; for (int i=1 ;i<n;i++){ int price = prices[i]-prices[i-1 ]; if (price>0 )ret+=price; } return ret; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 class Solution { public String removeKdigits (String num, int k) { int n = num.length(); Stack<Character> stack = new Stack <>(); for (int i=0 ;i<n;i++){ char c = num.charAt(i); while (!stack.isEmpty()&&k>0 &&c<stack.peek()){ stack.pop();k--; } stack.push(c); } while (k>0 &&!stack.isEmpty()){ stack.pop();k--; } StringBuilder sb = new StringBuilder (); while (!stack.isEmpty()){ char p = stack.pop(); sb.append(p); } sb.reverse(); while (sb.length()>0 && sb.charAt(0 )=='0' )sb.deleteCharAt(0 ); return sb.length()==0 ?"0" :sb.toString(); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public class Solution { public boolean canJump (int [] nums) { int n = nums.length; int rightmost = 0 ; for (int i = 0 ; i < n; ++i) { if (i <= rightmost) { rightmost = Math.max(rightmost, i + nums[i]); if (rightmost >= n - 1 ) { return true ; } } } return false ; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 class Solution { public List<Integer> partitionLabels (String s) { int n = s.length(); int [] right = new int [26 ]; List<Integer> ret = new ArrayList <>(); for (int i=0 ;i<n;i++){ right[s.charAt(i)-'a' ]=i; } int i=0 ; while (i<n){ int rightMost = right[s.charAt(i)-'a' ]; for (int j=i+1 ;j<rightMost;j++){ int jcRight = right[s.charAt(j)-'a' ]; if (jcRight>rightMost){ rightMost = jcRight; } } ret.add(rightMost-i+1 ); i = rightMost+1 ; } return ret; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 class Solution { public String removeDuplicateLetters (String s) { int n = s.length(); int [] right = new int [26 ]; for (int i=0 ;i<n;i++)right[s.charAt(i)-'a' ]=i; boolean [] visited = new boolean [26 ]; Deque<Character> stack = new ArrayDeque <>(); for (int i=0 ;i<n;i++){ char c = s.charAt(i); if (visited[c-'a' ])continue ; while (!stack.isEmpty() && stack.peek()> c && i < right[stack.peek()-'a' ]){ char p = stack.pop(); visited[p-'a' ] = false ; } stack.push(c); visited[c-'a' ]=true ; } StringBuilder sb = new StringBuilder (); while (!stack.isEmpty())sb.append(stack.pop()); return sb.reverse().toString(); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 class Solution { public String reorganizeString (String s) { char [] arr = s.toCharArray(); int n = arr.length; int [] count = new int [26 ]; for (char c : arr)count[c-'a' ]++; int maxIndex = 0 ; for (int i=0 ; i<count.length; i++){ if (count[i] > count[maxIndex]) maxIndex = i; } if (count[maxIndex] > (n+1 )/2 ) return "" ; char [] res = new char [n]; int i = 0 ; while (count[maxIndex]-- > 0 ){ res[i] = (char )('a' + maxIndex); i += 2 ; } for (int j=0 ; j<count.length; j++){ while (count[j]-- > 0 ){ if (i >= n) i = 1 ; res[i] = (char )('a' + j); i += 2 ; } } return String.valueOf(res); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 class Solution { public int maxEvents (int [][] events) { int n = events.length; Arrays.sort(events, ((o1,o2)->o1[0 ]-o2[0 ])); PriorityQueue<Integer> pq = new PriorityQueue <>(); int res = 0 ; int currDay = 1 ; int i = 0 ; while (i < n || !pq.isEmpty()) { while (i < n && events[i][0 ] == currDay) { pq.add(events[i][1 ]); i++; } while (!pq.isEmpty() && pq.peek() < currDay) { pq.remove(); } if (!pq.isEmpty()) { pq.remove(); res++; } currDay++; } return res; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 class Solution { public boolean isMatch (String s, String p) { int sRight = s.length(), pRight = p.length(); while (sRight > 0 && pRight > 0 && p.charAt(pRight - 1 ) != '*' ) { if (charMatch(s.charAt(sRight - 1 ), p.charAt(pRight - 1 ))) { --sRight; --pRight; } else { return false ; } } if (pRight == 0 ) { return sRight == 0 ; } int sIndex = 0 , pIndex = 0 ; int sRecord = -1 , pRecord = -1 ; while (sIndex < sRight && pIndex < pRight) { if (p.charAt(pIndex) == '*' ) { ++pIndex; sRecord = sIndex; pRecord = pIndex; } else if (charMatch(s.charAt(sIndex), p.charAt(pIndex))) { ++sIndex; ++pIndex; } else if (sRecord != -1 && sRecord + 1 < sRight) { ++sRecord; sIndex = sRecord; pIndex = pRecord; } else { return false ; } } return allStars(p, pIndex, pRight); } public boolean allStars (String str, int left, int right) { for (int i = left; i < right; ++i) { if (str.charAt(i) != '*' ) { return false ; } } return true ; } public boolean charMatch (char u, char v) { return u == v || v == '?' ; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class Solution { public boolean canAttendMeetings (int [][] intervals) { int n = intervals.length; if (n==0 )return true ; Arrays.sort(intervals,(o1,o2)->o1[0 ]-o2[0 ]); int end = intervals[0 ][1 ]; for (int i=1 ;i<n;i++){ int curStart = intervals[i][0 ]; if (curStart<end)return false ; end = intervals[i][1 ]; } return true ; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 class Solution { public int minMeetingRooms (int [][] intervals) { if (intervals==null ||intervals.length==0 ) return 0 ; PriorityQueue<Integer> queue = new PriorityQueue <Integer>(); Arrays.sort(intervals,(i,j)->i[0 ]-j[0 ]); queue.add(intervals[0 ][1 ]); for (int i=1 ;i!=intervals.length;i++) { int last=queue.peek(); if (last<=intervals[i][0 ]) { queue.poll(); queue.add(intervals[i][1 ]); }else { queue.add(intervals[i][1 ]); } } return queue.size(); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 class Solution { public int wiggleMaxLength (int [] nums) { int n = nums.length; if (n < 2 ) return n; int prevdiff = nums[1 ] - nums[0 ]; int ret = prevdiff != 0 ? 2 : 1 ; for (int i = 2 ; i < n; i++) { int diff = nums[i] - nums[i - 1 ]; if ((diff > 0 && prevdiff <= 0 ) || (diff < 0 && prevdiff >= 0 )) { ret++; prevdiff = diff; } } return ret; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 class Solution { public int [] advantageCount(int [] nums1, int [] nums2) { int m = nums1.length; int n = nums2.length; int [] ret = new int [m]; Arrays.sort(nums1); PriorityQueue<int []> queue = new PriorityQueue <>((o1,o2)->o2[0 ]-o1[0 ]); for (int i=0 ;i<n;i++)queue.offer(new int []{nums2[i],i}); int left = 0 ; int right = m-1 ; while (!queue.isEmpty()){ int [] pop = queue.poll(); int num = pop[0 ],index = pop[1 ]; if (nums1[right]>num){ ret[index] = nums1[right]; right--; }else { ret[index] = nums1[left]; left++; } } return ret; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 class Solution { public int eraseOverlapIntervals (int [][] intervals) { int n = intervals.length; if (n==0 )return 0 ; Arrays.sort(intervals,(o1,o2)->o1[1 ]-o2[1 ]); int ret = 1 ; int preEnd = intervals[0 ][1 ]; for (int i=1 ;i<n;i++){ if (intervals[i][0 ]>=preEnd){ ret++; preEnd = intervals[i][1 ]; } } return n-ret; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 public class Solution { public boolean winnerOfGame (String colors) { int n = colors.length(); int alice = 0 ,bob = 0 ; for (int i = 1 ; i < n-1 ; i++) { if (colors.charAt(i-1 )=='A' &&colors.charAt(i)=='A' &&colors.charAt(i+1 )=='A' )alice++; else if (colors.charAt(i-1 )=='B' &&colors.charAt(i)=='B' &&colors.charAt(i+1 )=='B' )bob++; } return alice>bob; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class Solution { public int [] diStringMatch(String s) { int n = s.length(); int [] ret = new int [n+1 ]; int low = 0 ,height = n; for (int i=0 ;i<n;i++){ ret[i] = s.charAt(i)=='I' ?low++:height--; } ret[n] = low; return ret; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 class Solution { String expression; public List<Integer> diffWaysToCompute (String expression) { int n = expression.length(); this .expression = expression; return dfs(0 ,n-1 ); } private List<Integer> dfs (int left,int right) { List<Integer> ret = new ArrayList <>(); for (int i=left;i<=right;i++){ char c = expression.charAt(i); if (c>='0' &&c<='9' )continue ; List<Integer> l1 = dfs(left,i-1 ),l2 = dfs(i+1 ,right); for (int a:l1){ for (int b:l2){ int cur = 0 ; if (c=='+' )cur = a+b; if (c=='-' )cur = a-b; if (c=='*' )cur = a*b; ret.add(cur); } } } if (ret.isEmpty()){ int cur = 0 ; for (int i=left;i<=right;i++)cur = cur * 10 + expression.charAt(i)-'0' ; ret.add(cur); } return ret; } }
相关资料