2018-10-03 19:29:43
Problem Description:
Problem solving:
Very interesting topic, the first thought is the violent traversal solution space, of course, also used to memo, unfortunately or tle, because time complexity is indeed a bit too high, it should be O (n!).
Map<linkedlist, integer> Map = new hashmap<> (); public int maxcoins (int[] nums) {if (nums.length = = 0) return 0; linkedlist<integer> list = new linkedlist<> (); for (int i:nums) list.add (i); return helper (list); } Private int Helper (linkedlist<integer> list) {if (list.size () = = 1) return list.get (0); if (Map.containskey (list)) return Map.get (list); int res = 1; arraylist<integer> arr = new arraylist<> (list); for (int i = 0; i < list.size (); i++) {int pre = i = = 0? 1:arr.get (i-1); int cur = arr.get (i); int next = i = = Arr.size ()-1? 1:arr.get (i + 1); List.remove (i); res = Math.max (res, PRE * cur * next + helper (list)); List.add (i, cur); } map.put (list, res); return res; }
The main subject gives the data scale, has already indicated that the time complexity is O (n^3) around more appropriate. The standard solution of the subject is given below, and the dynamic programming algorithm is used.
Dp[i][j]:nums[i] to Nums[j] The highest score you can get
DP[I][J] = max (Dp[i][k-1] + nums[i-1] * nums[k] * nums[j + 1] + dp[k + 1][j]) I <= k <= J//Pick one last burst balloon each time you can ask The scale of the problem declined
Adding padding to the original question can be more convenient to program.
public int maxcoins (int[] nums) { if (nums.length = = 0) return 0; int n = nums.length; int[] numspadding = new Int[n + 2]; Numspadding[0] = 1; Numspadding[n + 1] = 1; for (int i = 1; I <= n; i++) numspadding[i] = nums[i-1]; Int[][] dp = new Int[n + 2][n + 2]; for (int len = 1, Len <= N; len++) {for (int i = 1; I <= N-len + 1; i++) { int j = i + len-1; for (int k = i; k <= J; k++) { Dp[i][j] = Math.max (Dp[i][j], dp[i][k-1] + numspadding[i-1] * numspadding[k] * Numspadding[j + 1] + dp[k + 1][j]); }} return dp[1][n]; }
Dynamic planning-pop balloon Burst Balloons