Coins in a line II lintcode

public class Solution {
    /**
     * @param values: an array of integers
     * @return: a boolean which equals to true if the first player will win
     */
    public boolean firstWillWin(int[] values) {
        // write your code here
        int n=values.length;
        if(n<=2)
        return true;
        
         int max=0;
         int twomax=0;
         //贪心
         boolean turn =true;
         
         for(int i=0;i<n;i++){
             if(turn==true){
                 
             max+= values[i];
             if(i+1<n && values[i+1]>=values[i])
                 max+=values[++i];
                 
             }else{
                 
                 twomax+=values[i];
                 if(i+1<n && values[i+1]>=values[i])
                 twomax+=values[++i];
                 
             }
             
             turn =!turn;
         }
         
         if(max>twomax)
         return true;
         else
          return false;
         
        
    }
}

题目提示用动态规划,半天想不出来,其实用贪心完全可以。

两个人取的时候,决定是否取两个数的策略是看第二个数是否比第一个数大。计算两个人的最大值进行比较即可。



代码如下:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
This is a classic problem of finding the number of subsets of a given set with a certain property. In this case, we want to find the number of subsets of the set {0,1,2,...,k-1} such that the sum of the elements in the subset is less than or equal to n. We can use dynamic programming to solve this problem efficiently. Let dp[i][j] be the number of ways to choose a subset of the first i elements of the set {0,1,2,...,k-1} such that the sum of the elements in the subset is exactly j. Then the answer to the problem is the sum of dp[k][0] to dp[k][n]. The base case is dp[0][0]=1, since there is exactly one way to choose an empty subset with sum zero. For each i from 1 to k, we can either choose the i-th element or not. If we choose it, then we need to find the number of ways to choose a subset of the first i-1 elements with sum j-2i. If we do not choose it, then we need to find the number of ways to choose a subset of the first i-1 elements with sum j. Therefore, dp[i][j] = dp[i-1][j] + dp[i-1][j-2i], if j>=2i dp[i][j] = dp[i-1][j], otherwise The final answer is the sum of dp[k][0] to dp[k][n]. The time complexity of this algorithm is O(kn). Here is the Python code to solve the problem: ```python t = int(input()) for _ in range(t): n, k = map(int, input().split()) dp = [[0] * (n+1) for _ in range(k+1)] dp[0][0] = 1 for i in range(1, k+1): for j in range(n+1): dp[i][j] = dp[i-1][j] if j >= 2**i: dp[i][j] += dp[i-1][j-2**i] print(sum(dp[k])) ``` I hope this helps! Let me know if you have any more questions.

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值