LeetCode 题解工作台

最后一块石头的重量 II

有一堆石头,用整数数组 stones 表示。其中 stones[i] 表示第 i 块石头的重量。 每一回合,从中选出 任意两块石头 ,然后将它们一起粉碎。假设石头的重量分别为 x 和 y ,且 x 。那么粉碎的可能结果如下: 如果 x == y ,那么两块石头都会被完全粉碎; 如果 x != y ,…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 状态·转移·动态规划

bolt

答案摘要

两个石头的重量越接近,粉碎后的新重量就越小。同样的,两堆石头的重量越接近,它们粉碎后的新重量也越小。 所以本题可以转换为,计算容量为 `sum / 2` 的背包最多能装多少重量的石头。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

有一堆石头,用整数数组 stones 表示。其中 stones[i] 表示第 i 块石头的重量。

每一回合,从中选出任意两块石头,然后将它们一起粉碎。假设石头的重量分别为 x 和 y,且 x <= y。那么粉碎的可能结果如下:

  • 如果 x == y,那么两块石头都会被完全粉碎;
  • 如果 x != y,那么重量为 x 的石头将会完全粉碎,而重量为 y 的石头新重量为 y-x

最后,最多只会剩下一块 石头。返回此石头 最小的可能重量 。如果没有石头剩下,就返回 0

 

示例 1:

输入:stones = [2,7,4,1,8,1]
输出:1
解释:
组合 2 和 4,得到 2,所以数组转化为 [2,7,1,8,1],
组合 7 和 8,得到 1,所以数组转化为 [2,1,1,1],
组合 2 和 1,得到 1,所以数组转化为 [1,1,1],
组合 1 和 1,得到 0,所以数组转化为 [1],这就是最优值。

示例 2:

输入:stones = [31,26,33,21,40]
输出:5

 

提示:

  • 1 <= stones.length <= 30
  • 1 <= stones[i] <= 100
lightbulb

解题思路

方法一:动态规划

两个石头的重量越接近,粉碎后的新重量就越小。同样的,两堆石头的重量越接近,它们粉碎后的新重量也越小。

所以本题可以转换为,计算容量为 sum / 2 的背包最多能装多少重量的石头。

定义 dp[i][j] 表示从前 i 个石头中选出若干个,使得所选石头重量之和为不超过 j 的最大重量。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
    def lastStoneWeightII(self, stones: List[int]) -> int:
        s = sum(stones)
        m, n = len(stones), s >> 1
        dp = [[0] * (n + 1) for _ in range(m + 1)]
        for i in range(1, m + 1):
            for j in range(n + 1):
                dp[i][j] = dp[i - 1][j]
                if stones[i - 1] <= j:
                    dp[i][j] = max(
                        dp[i][j], dp[i - 1][j - stones[i - 1]] + stones[i - 1]
                    )
        return s - 2 * dp[-1][-1]
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidate understands dynamic programming and state transitions.

  • question_mark

    Able to relate the problem to the subset-sum pattern with both addition and subtraction.

  • question_mark

    Can efficiently optimize the solution by tracking achievable states and minimizing the result.

warning

常见陷阱

外企场景
  • error

    Forgetting to handle negative weights and possible sum ranges.

  • error

    Not considering all possible combinations of pairings during the stone smash process.

  • error

    Overcomplicating the problem by trying to brute force every possible combination without using dynamic programming.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Increasing the number of stones to test the scalability of the approach.

  • arrow_right_alt

    Allowing negative weights for stones to introduce more complexity in the calculations.

  • arrow_right_alt

    Introducing additional constraints, such as limiting the number of smashes or requiring a specific stone pairing order.

help

常见问题

外企场景

最后一块石头的重量 II题解:状态·转移·动态规划 | LeetCode #1049 中等