375. Guess Number Higher or Lower II

来源:互联网 发布:python视频教程 廖雪峰 编辑:程序博客网 时间:2024/06/02 06:05

原题:

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.

Example:

n = 10, I pick 8.First round:  You guess 5, I tell you that it's higher. You pay $5.Second round: You guess 7, I tell you that it's higher. You pay $7.Third round:  You guess 9, I tell you that it's lower. You pay $9.Game over. 8 is the number I picked.You end up paying $5 + $7 + $9 = $21.

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

题意比较难理解:是猜数字游戏,但是每次你猜的数字是几,如果你猜错了就得支付几元。不是诸葛亮的二分法就可以解决的。要求返回你确保能解决这个问题所要的最少钱数。


思考过程 & 解题思路:递归算法,遍历所有情况。cost(begin,end)函数返回(begin,end)区间的最便宜的解法,它会遍历begin和end之间所有正数,遍历i时表示此次猜的数字是i的情况,那么花费  i + Math.max(cost(begin,i - 1),cost(i + 1,end)。不断递归。一开始这样硬解,超时了。后来用哈希表存储已经遍历过的区间,n = 200时也超时了。后来发现这是滥用哈希表,哈希表是用来查key的,查不知道索引的key。完全可以把遍历过的区间存到数组里。最后accepted了。


AC代码:

int[][] memory = new int[201][201];//用于记录已经遍历过的区间,之所以是201,是因为检测案例中n最大为201.如果n最大为x,那数组上限就设置成x+1    public int getMoneyAmount(int n) {        return cost(1,n);    }    public int cost(int begin,int end){        if (begin >= end) return 0;        if (memory[begin][end] != 0) return memory[begin][end];//如果已经遍历过就返回        int ret = Integer.MAX_VALUE;        for (int i = begin;i <= end;i++)            ret = Math.min(ret,i + Math.max(cost(begin,i - 1),cost(i + 1,end)));//第一次猜的数字是i,不断递归,更新ret        memory[begin][end] = ret;//新的区间添加到memory里        return ret;    }


原创粉丝点击