LeetCode刷题笔记 375. 猜数字大小 II

这是一个关于猜数字游戏的题目,玩家需要猜测1到n之间的数字,每次猜测错误会根据错误数字支付相应金额。游戏结束时,玩家需支付所有错误猜测的总金额。本篇博客总结了使用动态规划(DP)解决此类问题的方法,包括如何通过拆分区间寻找最小开销的子问题,并给出了优化DP的思路。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

我们正在玩一个猜数游戏,游戏规则如下:

我从 1 到 n 之间选择一个数字,你来猜我选了哪个数字。

每次你猜错了,我都会告诉你,我选的数字比你的大了或者小了。

然而,当你猜了数字 x 并且猜错了的时候,你需要支付金额为 x 的现金。直到你猜到我选的数字,你才算赢得了这个游戏。

示例:
n = 10, 我选择了8.

第一轮: 你猜我选择的数字是5,我会告诉你,我的数字更大一些,然后你需要支付5块。
第二轮: 你猜是7,我告诉你,我的数字更大一些,你支付7块。
第三轮: 你猜是9,我告诉你,我的数字更小一些,你支付9块。

游戏结束。8 就是我选的数字。

你最终要支付 5 + 7 + 9 = 21 块钱。

总结

抽象的数组往往拥有抽象的排列,就像这题的DP:
在这里插入图片描述
在判断(1, 3)的数时,Math.max调用的是(1,0)(2,3)和(1, 1)(3, 3),即“前半段”是横向循环,“后半段”是竖向循环。

暴力二分法(超时)

public class Solution {
    public int getMoneyAmount(int n) {
        return calculate(1, n);
    }

    public int calculate(int low, int high) {
        if (low >= high)
            return 0;
        int minres = Integer.MAX_VALUE;
        for (int i = (low+high) / 2; i <= high; i++) {
            int res = i + Math.max(calculate(i+1, high), calculate(low, i-1));
            minres = Math.min(res, minres);
        }

        return minres;
    }
}

DP

以 i 为第一次尝试找到最小开销的过程可以被分解为找左右区间内最小开销的子问题。对于每个区间,我们重复问题拆分的过程,得到更多子问题
在这里插入图片描述
在这里插入图片描述

注意:这张图下标为零的地方没有画出来

class Solution {
    public int getMoneyAmount(int n) {
        int[][] dp = new int[n+1][n+1];
        for(int len = 2; len <= n; len++) {
            for(int start = 1; start <= n - len + 1; start++) {
                int res = Integer.MAX_VALUE;	// len:3,start:1,piv:2
                for(int piv = start; piv < start + len - 1; piv++) {
                    int min = piv + Math.max(dp[start][piv-1], dp[piv+1][start+len-1]);
                    res = Math.min(res, min);
                }
                dp[start][start+len-1] = res;
            }
        }

        return dp[1][n];    
    }
}

优化DP
在这里插入图片描述

class Solution {
    public int getMoneyAmount(int n) {
        int[][] dp = new int[n+1][n+1];
        for(int len = 2; len <= n; len++) {
            for(int start = 1; start <= n - len + 1; start++) {
                int res = Integer.MAX_VALUE;
                // 下面是唯一改动的地方
                for(int piv = start + (len - 1) / 2; piv < start + len - 1; piv++) {
                    int min = piv + Math.max(dp[start][piv-1], dp[piv+1][start+len-1]);
                    res = Math.min(res, min);
                }
                dp[start][start+len-1] = res;
            }
        }

        return dp[1][n];    
    }
}

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/guess-number-higher-or-lower-ii

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值