464.Can I Win

Link:https://leetcode.com/problems/can-i-win/?tab=Description

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, two players might take turns drawing from a common pool of numbers of 1..15 without replacement until they reach a total >= 100.

Given an integermaxChoosableIntegerand another integerdesiredTotal, determine if the first player to move can force a win, assuming both players play optimally.

You can always assume thatmaxChoosableIntegerwill not be larger than 20 anddesiredTotalwill not be larger than 300.

Example

Input:

maxChoosableInteger = 10
desiredTotal = 11

Output:
false

Explanation:
No matter which integer the first player choose, the first player will 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 integers from 2 up to 10.
The second player will win by choosing 10 and get a total = 11, which is 
>
= desiredTotal.
Same with other integers chosen by the first player, the second player will always win.

Solution: DP(Top To Down)

public class Solution {
    public boolean canIWin(int maxChoosableInteger, int desiredTotal) {
        if (maxChoosableInteger < 0 || desiredTotal < 0) {
            throw new IllegalArgumentException("the input is invalid");
        }
        int sum = (1 + maxChoosableInteger) * maxChoosableInteger / 2;
        if (sum < desiredTotal) {
            return false;
        }
        if (desiredTotal == 0) {
            return true;
        }

        int[] state = new int[maxChoosableInteger];
        Map<String, Boolean> memo = new HashMap<>();
        return canIWinHelper(maxChoosableInteger, desiredTotal, state, memo, 0);
    }

    private boolean canIWinHelper(int maxChoosableInteger, int desiredTotal, 
                                  int[] state, Map<String, Boolean> memo, int tmpSum) {
        String stateStr = Arrays.toString(state);
        if (memo.containsKey(stateStr)) {
            return memo.get(stateStr);
        }

        for (int num = 1; num <= maxChoosableInteger; num ++) {
            int numIndex = num - 1;
            if (state[numIndex] == 1) {
                continue;
            }

            state[numIndex] = 1;
            if (tmpSum + num >= desiredTotal || !canIWinHelper(maxChoosableInteger, desiredTotal, state, memo, tmpSum + num)) {
                state[numIndex] = 0;
                memo.put(stateStr, true);
                return true;
            }
            state[numIndex] = 0;
        }

        memo.put(stateStr, false);
        return false;
    }
}

Time Limited Exceeded

class Solution(object):
    def canIWin(self, maxChoosableInteger, desiredTotal):
        """
        :type maxChoosableInteger: int
        :type desiredTotal: int
        :rtype: bool
        """
        if maxChoosableInteger <= 0 or desiredTotal < 0:
            raise ValueError('the input is invalid')

        sum = (1 + maxChoosableInteger) * maxChoosableInteger / 2
        if sum < desiredTotal:
            return False
        if desiredTotal == 0:
            return True

        num_set = set()
        state = [False for _ in xrange(maxChoosableInteger)]
        memo = dict()
        return self.can_i_win_helper(maxChoosableInteger, desiredTotal, state, 0, memo)

    def can_i_win_helper(self, max_choosable_int, desired_total, state, tmp_sum, memo):
        state_str = ','.join([str(x) for x in state])
        if state_str in memo:
            return memo[state_str]

        for num in xrange(1, max_choosable_int + 1):
            num_index = num - 1
            if state[num_index]:
                continue

            state[num_index] = True
            if tmp_sum + num >= desired_total or\
               not self.can_i_win_helper(max_choosable_int, desired_total, state, tmp_sum + num, memo):
                   state[num_index] = False
                   memo[state_str] = True
                   return True

            state[num_index] = False

        memo[state_str] = False
        return False
class Solution(object):
    def canIWin(self, maxChoosableInteger, desiredTotal):
        """
        :type maxChoosableInteger: int
        :type desiredTotal: int
        :rtype: bool
        """
        if maxChoosableInteger <= 0 or desiredTotal < 0:
            raise ValueError('the input is invalid')

        sum = (1 + maxChoosableInteger) * maxChoosableInteger / 2
        if sum < desiredTotal:
            return False
        if desiredTotal == 0:
            return True

        num_set = set()
        return self.can_i_win_helper(maxChoosableInteger, desiredTotal, num_set, 0)

    def can_i_win_helper(self, max_choosable_int, desired_total, num_set, tmp_sum):
        for num in xrange(1, max_choosable_int + 1):
            if num in num_set:
                continue

            num_set.add(num)
            if tmp_sum + num >= desired_total or\
               not self.can_i_win_helper(max_choosable_int, desired_total, num_set, tmp_sum + num):
                   num_set.remove(num)
                   return True
            num_set.remove(num)

        return False

results matching ""

    No results matching ""