LC1049.最后一块石头的重量II

问题

问题

题解

  • 考虑到最后合并的时候两堆越接近石头重量总和的一半,则差值最小
  • 由于是随机拿石头,因此转换为用一个背包重量为sum/2的背包去石头堆里找石头,尽量让背包装满
  • 以上分析后题目变成0-1背包问题
class Solution {
    public int lastStoneWeightII(int[] stones) {
        int n = stones.length;
        int sum = 0;
        for(int stone : stones){
            sum += stone;
        }
        int[] dp = new int[sum / 2 + 1];
        for(int i = 0; i < n; i ++){
            for(int j = sum / 2; j >= stones[i]; j --){
                dp[j] = Math.max(dp[j - stones[i]] + stones[i], dp[j]);
            }
        }
        return sum - dp[sum / 2] * 2;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41423750/article/details/107007512