leetcode 375. Guess Number Higher or Lower II 解题小结

题目是这样子的,跟374很像:

We are playing the Guess Game. The game is as follows:

I pick a number from 1 to n. You have to guess which number I picked.

Every time you guess wrong, I'll tell you whether the number I picked is higher or lower.

However, when you guess a particular number x, and you guess wrong, you pay $x. You win the game when you guess the number I picked.

Given a particular n ≥ 1, find out how much money you need to have to guarantee a win.

题目大意还是猜数游戏,不过这次的重点换了,题目要求你猜错了就得付与你所猜的数目一致的钱,最后应求出保证你能赢的钱数(即求出保证你获胜的最少的钱数),题目的提示是动态规划,自己吃的不太透,想着之前做过的动态规划都是从初始条件出发,再推出后面的值,于是就噗嗤噗嗤地写了前面几种情况在找规律,算了下,发现max(后四位的所应判断的钱数,倒数第四位的钱数+前面的钱数)好像挺有可能的,但提交的时候发现n大于19时就统统过不了了,于是果断否决了自己的想法,因为找规律这个想法完全说服不了自己为什么这样求出的是最小值,在这里也给自己敲了一个警钟,不要试图用侥幸的心理来蒙骗自己,网上了搜一番后,发现没有讲的比较清楚的博客,统统都是贴代码(っ*´Д`)っ(理解不了了喂),后面在leetcode的discuss里面有两句英文让自己一下子就懂了.

具体是这样的,在1-n个数里面,我们任意猜一个数(设为i),保证获胜所花的钱应该为 i + max(w(1 ,i-1), w(i+1 ,n)),这里w(x,y))表示猜范围在(x,y)的数保证能赢应花的钱,则我们依次遍历 1-n作为猜的数,求出其中的最小值即为答案,即最小的最大值问题

for(int i = start; i<end+1;i++)
        {
            int temp = i+max(cost(a,start,i-1),cost(a,i+1,end));
            if(temp<res)
            {
                res = temp;
            }
        }

这是这道题的核心部分,temp即为所猜的数对应保证能赢的钱数,res为最后的答案,最后AC的代码为:

class Solution {
public:
    int getMoneyAmount(int n) {
        int **dp;
        dp = new int *[n+1];
        for(int i =0 ;i<n+1;i++)
        {
            dp[i]= new int[n+1];
        }
        for(int i = 0 ;i<n+1; i++)
        {
            for(int j = 0; j< n+1; j++)
            {
                dp[i][j]=0;
            }
        }
        return cost(dp,1,n);
    }
    
    int cost(int **a,int start, int end)
    {   
        int res = INT_MAX; 
        if(start>=end)
        {
            return 0;
        }
        if(a[start][end]!=0)
        {
            return a[start][end];
        }
        for(int i = start; i<end+1;i++)
        {
            int temp = i+max(cost(a,start,i-1),cost(a,i+1,end));
            if(temp<res)
            {
                res = temp;
            }
        }
        a[start][end] = res;
        return res;
    }
};


  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值