publicintmaxCoins(int[] nums){ boolean[] flag = newboolean[nums.length]; this.c = 0; int r = burst(nums, flag, 0); System.out.println(c); return r; }
publicintburst(int[] nums, boolean[] flag, int count){ int max = 0; int n = nums.length;
if (count == n) // 戳够了足够多的气球之后,就不戳了 return0; for (int i = 0; i < n; i++) { // 遍历气球数组 if (!flag[i]) { // 如果当前气球没有被戳过 flag[i] = true; // 标记当前气球为已戳
int res = find(nums, flag, i) * nums[i] + burst(nums, flag, count + 1); // 计算戳当前气球能拿到的分数,然后递归剩下的气球 if (res > max) { max = res; // 更新最大值 }
flag[i] = false; // 回溯,把戳过的气球还原 } } return max; }
publicintfind(int[] nums, boolean[] flag, int cur){ // find 方法是找到当前气球的前一个和后一个,相乘并返回 this.c += 1; // 计数 int i = cur; int pre = 1; int next = 1; cur -= 1; while (cur >= 0) { if (!flag[cur]) { pre = nums[cur]; break; } cur -= 1; } cur = i + 1; while (cur < nums.length) { if (!flag[cur]) { next = nums[cur]; break; } cur += 1; } return pre * next; } }