Coins in a line

Source: Internet
Author: User

There is n coins in a line. Players take turns to take one or both coins from right side until there is no more coins left. The player who has the last coin wins.

Could decide the first play would win or lose?

This is the DP problem of a class of game.

The basic solution to the game problem is:

State: Defines the status of one person.

Function: Consider the status of two people to do the update, that is, according to a relationship against each other to make decisions.

The game class topic is suitable from the large state to the small state recursion, is very suitable for the memory search. But the problem itself is relatively simple, can have been bottom-up to do.

This analysis F[i] for the remaining I coin when the initiator can win. We consider a recursive state. The initiator in F[i] can win, that is, he took the last one or two coins. This is f[i-1] the latter f[i-2] when the hand wins, so there is a recursive relationship f[i] =!f[i-1]| |! F[i-2]

Initialization, there are 0 coins left when the initiator must lose. There are 1 or 2 coins left to win. But what does the final result take? There are 0 coins left, or n pieces. Actually we are from still have n coin, consider this time of game state consideration, so is f[n]. The code is as follows:

classSolution:#@param n:an Integer    #@return: A Boolean which equals to True if the first player would win    defFirstwillwin (self, n):ifN <=0:returnFalseifN <= 2:            returnTrue F= [False] * (n+1) f[1] =True f[2] =True forIinchXrange (2,n+1): F[i]= ( notF[I-1])or( notF[i-2])                    returnF[n]

Coins in a line

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.