can I win(judge first player to move can win)

本文探讨了一种新颖的游戏机制,玩家在无重复的情况下从有限整数池中抽取数字,目标是使总和超过100以获胜。文章提供了实现胜利策略的代码,通过优化算法确定第一轮玩家是否能确保胜利。

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

/* 
    In "the 100 game," two players take turns adding, to a running 
    total, any integer from 1..10. The player who first causes the running 
    total to reach or exceed 100 wins. 
    What if we change the game so that players cannot re-use integers? 
    For example, if two players might take turns drawing from a common pool of numbers 
    of 1..15 without replacement until they reach a total >= 100. This problem is 
    to write a program that determines which player would win with ideal play. 

    Write a procedure, "Boolean canIWin(int maxChoosableInteger, int desiredTotal)", 
    which returns true if the first player to move can force a win with optimal play. 

    Your priority should be programmer efficiency; don't focus on minimizing 
    either space or time complexity. 
*/ 

Boolean canIWin(int maxChoosableInteger, int desiredTotal) { 
// Implementation here. Write yours 

}

Solution from here http://codeanytime.blogspot.com/2015/01/caniwin.html

//The catch is: when the largest number remaining is greater than the target remaining, the player is sure to win
//helper returns true if the CURRENT player can win
public boolean canIWin(int max, int target) {
    List<Integer> candidates = new ArrayList<Integer>();
    for (int i = 1; i <= max; i++){
        candidates.add(i);
    }
    return helper(candidates, target);
}

public boolean helper(List<Integer> candidates, int target){
    if (candidates.get(candidates.size()-1) >= target){
        return true;
    }
    for (int i = 0; i < candidates.size(); i++){
        int removed = candidates.remove(i);
        if (!helper(candidates, target-removed)){
            candidates.add(i, removed);
            return true;
        }
        candidates.add(i, removed);
    }
    return false;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值