Leetcode464-can I Win-medium

Source: Internet
Author: User
Tags bitwise

In the "game," the "turns" of the "players take", "adding" and "to a running" of total, any integer from 1..10. The player first causes the running total to reach or exceed wins.

What if we change the game so that players cannot re-use integers?

For example, the players might take turns drawing from a common pool of numbers of 1..15 without replacement until re Ach a total >= 100.

Given an integer maxChoosableInteger and another integer desiredTotal , determine if the first player to move can force a win, assuming both PLA Yers play optimally.

You can always assume that would not be larger than and would not be maxChoosableInteger desiredTotal larger than 300.

Example

Input:maxchoosableinteger = 10desiredTotal = 11output:falseexplanation:no matter which integer the first player choose, th E first player would lose. The first player can choose an integer from 1 up to 10.If the first player choose 1, the second player can only choose int Egers from 2 up to 10.The second player would win by choosing and get a total = one, which is >= desiredtotal.same wit h other integers chosen by the first player, the second player would always win.

Algorithm:

1. And the front of the stone game very much like, can still from the front of the state transfer equation can be used to learn from the place, that is, we win the method or, to test the number of different feasible stones, if any successful will be placed in the other side must lose state, can be. However, it becomes difficult to add the restriction that cannot be repeated, and the method of decoding is DFS, which is the possibility to traverse the order of each sort. Use a boolean[] array to record used numbers, traverse every possible, brute force hack.

2. Optimization of time complexity. The simple DFS will be tle, because recursion to the bottom is expensive, and many of the same sub-states are computed repeatedly. So we should record the Boolean result of a state in the middle, if we traverse to a state to find out the results can be returned directly.

Question: How to define a state? At first thought to be 1. Used number Case 2. Total together is a state, and later found that a single 1 is enough, because in a particular problem, MaxI is always fixed, if you 1 fixed, MaxI-all the used numbers are 2, that 2 also fixed. So 2 is included in the 1. So in the end, just use a map< with a number of cases,boolean> to do memo.

Question: How to express the use of the case of a number, here is an optimization, do not use boolean[] isused to express, so that the map to index to the words each time to open a new boolean[], space consumption. The subject gives a limit to the number of available numbers no more than 20, using it you can use int to replace boolean[]. That is, each of the integers on the 0 or one as a Boolean result. such as Tfft with 1001来 expression. Marking a number has been used to convert to a bitwise operation. isused = isused ^ (1 << (number-1)). A bitwise XOR or 1 is a reversal.

Details:

1. This DFS changes the status of the mark isused each change must appear in pairs, changed, recursive, change back. The subject is also to remember in the for loop to change the head and tail, the middle of the direct return to change (just the case of the basic data type with an Int. record state, if it is return the word itself is not preserved, you can not change back).

2. Judging victory has two conditions, one is this step to win (can take the number of higher than the limit), one is in the future I will certainly win (I have a few of the desirable methods will let the opponent into a lost place). Don't miss out on the first kind.

3. Put memo is the first time you call this function isused state, and not after you change, be careful!

4. Bit operation when possible or enclosed in parentheses to ensure the order of operations, there are several priority is really difficult to remember, insurance.

5. The boundary conditions are interesting, one is if the first desirable number is greater than the border, and win; one is if you two have all the numbers out of the border, the game doesn't make sense, you all lose.

1. My implementation

classSolution { Public BooleanCaniwin (intMaxchoosableinteger,intdesiredtotal) {                //boundary conditions are interesting .        if(Maxchoosableinteger >=desiredtotal) {            return true; }        if((1 + maxchoosableinteger) * MAXCHOOSABLEINTEGER/2 <desiredtotal) {            return false; } Map<integer, Boolean> memo =NewHashmap<>(); returnHelper (Maxchoosableinteger, desiredtotal, 0, Memo); }        Private BooleanHelperintMaxI,intTotalintisused, Map<integer, boolean>Memo) {                if(Memo.containskey (isused)) {returnMemo.get (isused); }                 for(inti = 1; I <= MaxI; i++) {            //Be sure to expand the previous calculation, = = Priority ratio & High            if(((isused >> (i-1) & 1) = = 1) {                Continue; }            //a certain XOR 1 is reversing this bit! The reversal here is to change the state of the mark with No. isused = isused ^ (1 << (i-1)); //Note that I >= total when the verdict is victory, in fact, the equivalent of the export to dissolve here.             if(I >= Total | |!helper (MaxI, Total-I, isused, Memo)) {                //here to return to the former is supposed to change the use of the state back, but only Java just passed the reference parameter, back to the original will not be retained, so it is omitted. //It is important to note that you have not changed the state of the memo!! You didn't change it! isused = isused ^ (1 << (i-1)); Memo.put (isused,true); return true; }            //It's important to remember to restore the changed state back, because the for loop is inside the function and shares the variable, so changing it back doesn't affect the next variable. isused = isused ^ (1 << (i-1)); } memo.put (isused,false); return false; }    }

2. My implementation get rid of annotations easy to read version

classSolution { Public BooleanCaniwin (intMaxchoosableinteger,intdesiredtotal) {                if(Maxchoosableinteger >=desiredtotal) {            return true; }        if((1 + maxchoosableinteger) * MAXCHOOSABLEINTEGER/2 <desiredtotal) {            return false; } Map<integer, Boolean> memo =NewHashmap<>(); returnHelper (Maxchoosableinteger, desiredtotal, 0, Memo); }        Private BooleanHelperintMaxI,intTotalintisused, Map<integer, boolean>Memo) {                if(Memo.containskey (isused)) {returnMemo.get (isused); }                inttemp =isused;  for(inti = 1; I <= MaxI; i++) {            if(((isused >> (i-1) & 1) = = 1) {                Continue; } isused= isused ^ (1 << (i-1)); if(I >= Total | |!helper (MaxI, Total-I, isused, Memo)) {Memo.put (temp,true); return true; } isused= isused ^ (1 << (i-1)); } memo.put (temp,false); return false; }}

3. Chapter Nine Implementation version

/*** This reference procedure comes from the nine chapter algorithm, which is provided by the @ Nine chapter algorithm. All rights reserved, please specify the source of the forwarding. *-Nine chapters The algorithm is committed to helping more Chinese to find a good job, the teachers team from Silicon Valley and the domestic first-line large companies in-service engineers. *-existing interview training courses include: Nine Chapters algorithm class, System design class, algorithm intensive class, Java beginner and Basic algorithm class, Android project actual combat class, *-Big Data Project actual combat class, algorithm interview high frequency problem class, dynamic planning special class *-more details please see the official website:Http://www.jiuzhang.com/?source=code*/  Public classSolution {int[] DP; Boolean[] used;  Public BooleanCaniwin (intMaxchoosableinteger,intdesiredtotal) {        intsum = (1 + maxchoosableinteger) * MAXCHOOSABLEINTEGER/2; if(Sum < Desiredtotal) {//take all the numbers, and not reach the desiredtotal, can not win the game            return false; }        if(Desiredtotal <= Maxchoosableinteger) {//The first step is to get Victory .            return true; } DP=New int[1 <<Maxchoosableinteger]; Arrays.fill (DP,-1); Used=New Boolean[Maxchoosableinteger + 1]; returnHelper (desiredtotal); }         Public BooleanHelperintdesiredtotal) {        if(desiredtotal <= 0) {            return false; }        intKey = Format (used);//Convert The used array to decimal notation        if(Dp[key] = =-1){              for(inti = 1; i < used.length; i++) {//enumerating the numbers that are not selected                if(!Used[i]) {Used[i]=true; if(!helper (Desiredtotal-i)) {Dp[key]= 1; Used[i]=false; return true; } Used[i]=false; }} Dp[key]= 0; }        returnDp[key] = = 1; }        Public intFormatBoolean[] used) {        intnum = 0;  for(Booleanb:used) {num<<= 1; if(b) {num|= 1; }        }        returnnum; }}

Leetcode464-can I Win-medium

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.