1. 题目描述
在某射击场有N个靶,每个靶上都有一个分数,存在score数组中。击中第i个靶的得分为score[left]* score[i]* score[right],同时原left和right两个靶变为相邻的靶。其中得分为0的靶是不能射击的,当left不存在或者不能射击时,得分为score[i]* score[right],同理right也遵循此规则;当left和right都不存在或者不能射击时,得分为score[i]。请计算出击中所有能射击的靶,最多能得多少分?
2. 参考题目
312. Burst Balloons
3. 我的做法
参考leetcode的Discuss进行改写,如有问题,欢迎指教
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
Listlist=new ArrayList();
int size = scanner.nextInt();
for(int i = 0; i< size ; i++)
list.add(scanner.nextInt());
process(list);
}
scanner.close();
}
public static void process(List list){
Listtmplist=new ArrayList();
int sum = 0;
int size = list.size();
for(int i=0;i
if(list.get(i)!=0)
tmplist.add(list.get(i));
else{
int []a=new int[tmplist.size()];
for(int j=0;j
a[j]=tmplist.get(j);
}
sum+=maxRanks(a);
tmplist.clear();
}
if(i==size-1){
int []a=new int[tmplist.size()];
for(int j=0;j
a[j]=tmplist.get(j);
}
sum+=maxRanks(a);
}
}
System.out.println(sum);
}
public static int maxRanks(int[] iNums) {
int[] nums = new int[iNums.length + 2];
int n = 1;
for (int x : iNums)
if (x > 0) nums[n++] = x;
nums[0] = nums[n++] = 1;
int[][] memo = new int[n][n];
return burst(memo, nums, 0, n - 1);
}
public static int burst(int[][] memo, int[] nums, int left, int right) {
if (left + 1 == right)
return 0;
if (memo[left][right] > 0)
return memo[left][right];
int ans = 0;
for (int i = left + 1; i < right; ++i)
ans = Math.max(ans, nums[left] * nums[i] * nums[right]
+ burst(memo, nums, left, i) + burst(memo, nums, i, right));
memo[left][right] = ans;
return ans;
}
}