[LintCode]Coins in a Line

这作为dp的经典题,回头来看,启发良多。
之前在string 背景的 dp题目中,总结了很多解决dp题目的思维模式与技巧。 主要包括 方向性(向‘之前’ 看,解决之后的问题)。 矩阵提示法,上一行? 上一列的意义,联系实际问题的意义。

这俩道coin的题目,一个一维,一个二维,但实质是一个题目。 
关于方向性,不管是前还是后,实质是指向subproblem的。 这俩题的解法核心都是如此,确定final problem,和 subproblem。然后从最小问题一直构建到final problem

那么第一题的final problem是  在位置0的时候,先拿的人能否赢? 
第二题的final problem则是,在取 0—n-1 这一段时,先拿的人能否赢? 

    //启发根源来自于这个题目version2。在version2的基础上,如何能够发现version3的类似解法。
    //题目
    //There are n coins with different value in a line. 
    //Two players take turns to take one or two coins from left side until there are no more coins left.
    //The player who take the coins with the most value wins.
    //Could you please decide the first player will win or lose?
    
    
    public boolean firstWillWin(int[] values) {
        // write your code here
        if(values.length < 3)
            return true;
        int len = values.length;
        int[] dp = new int[len];
        dp[len-1] = values[len-1];
        dp[len-2] = values[len-1] + values[len-2];
        for(int i=len-3; i>=0; i--){
            dp[i] = Math.max(values[i] - dp[i+1], values[i] + values[i+1] - dp[i+2]);
        }
        return dp[0] > 0;
    }

    //There are n coins in a line. Two players take turns to take a coin from one of the ends of the line 
    //until there are no more coins left. The player with the larger amount of money wins.
    //Could you please decide the first player will win or lose?
    //Recursion
    public boolean firstWillWin(int[] values) {
        // write your code here
        int len = values.length;
        if(len < 2)
            return true;
        int res = helper(values, 0, len-1);
        return res > 0;
    }
    
    public int helper(int[] values, int s, int e){
        if(s==e)
            return values[s];
        return Math.max(values[s] - helper(values, s+1,e), values[e] - helper(values, s , e-1));
    }
    
    //DP
    public boolean firstWillWin(int[] values) {
        // write your code here
        int len = values.length;
        int[][] dp = new int[len][len];
        dp[len-1][len-1] = values[len-1];
        for(int i=len-2; i>=0; i--){
            dp[i][i] = values[i];
            for(int j = i+1; j
   
   
    
     0;
    }
   
   


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值