There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] denotes a balloon whose horizontal diameter stretches between xstart and xend. You do not know the exact y-coordinates of the balloons.

Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with xstart and xend is burst by an arrow shot at x if xstart <= x <= xend. There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.

Given the array points, return the minimum number of arrows that must be shot to burst all balloons.

Example 1:

Input: points = [[10,16],[2,8],[1,6],[7,12]] Output: 2 Explanation: The balloons can be burst by 2 arrows: - Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6]. - Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12].

Example 2:

Input: points = [[1,2],[3,4],[5,6],[7,8]] Output: 4 Explanation: One arrow needs to be shot for each balloon for a total of 4 arrows.

Example 3:

Input: points = [[1,2],[2,3],[3,4],[4,5]] Output: 2 Explanation: The balloons can be burst by 2 arrows: - Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3]. - Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5].

Constraints:

  • 1 <= points.length <= 105
  • points[i].length == 2
  • -231 <= xstart < xend <= 231 - 1

当我看到这道题目的时候,我的第一反应是——DP。记得之前我曾形容过一些题目『长着一张DP的脸』,现在看来可能是我看什么都长着一张DP的脸。

一个常见的说法是:能用贪心解决的问题一般也能用动态规划解决。不过通过这一题我了解到:有时候贪心算法比动态规划好用很多。而且贪心算法也不是完全无迹可寻:如果一个问题有局部最优解,那么很可能就要用到贪心;而动态规划中下一个子问题是从上一个子问题推出的。

在参考答案写出贪心写法后,我又尝试写出了动态规划的写法。可是这实在非常强行:如果我想出了适用与于动态规划的写法,那我很大概率已经想出了贪心的解法了。这更像是一种改写。

贪心:

/** * @param {number[][]} points * @return {number} */ var findMinArrowShots = function(points) { let count = 1 points = points.sort((p, c) => p[1] -c[1]) let max = points[0][1] for (let i=1; i<points.length; i++) { if (points[i][0] > max) { count++ max = points[i][1] } } return count };

动态规划:

/** * @param {number[][]} points * @return {number} */ var findMinArrowShots = function(points) { const dp = [] points = points.sort((p, c) => p[1] -c[1]) let flag = points[0][1] for (let i=0; i < points.length; i++) { if (i === 0) { dp[0] = 1 continue } let [start, end] = points[i] if (start <= flag) { dp[i] = dp[i-1] } else { dp[i] = dp[i-1]+1 flag = end } } return dp.pop() };