LeetCode 3320: Count The Number of Winning Sequences

Problem Description

Explanation

To solve this problem, we can use dynamic programming to keep track of the number of winning sequences Bob can use to beat Alice for each possible ending move Bob makes in the current round. We initialize a 3D dynamic programming array dp where dp[i][j][k] represents the number of winning sequences Bob can use to beat Alice after i rounds, where the last move Bob made was creature j and the last move Alice made was creature k.

At each round, we iterate over all possible moves for Bob and Alice and update the dp array based on the rules mentioned in the problem statement. Finally, we sum up all winning sequences for Bob with different ending moves and return the total count modulo 10^9 + 7.

Time Complexity

The time complexity of this solution is O(n) where n is the length of the input string s.

Space Complexity

The space complexity of this solution is O(n) to store the 3D dynamic programming array.

Solutions

class Solution {
    public int countTheNumberOfWinningSequences(String s) {
        int mod = 1000000007;
        int n = s.length();
        long[][][] dp = new long[n + 1][3][3];
        
        for (int k = 0; k < 3; k++) {
            dp[1][k][k] = 1;
        }
        
        for (int i = 2; i <= n; i++) {
            for (int j = 0; j < 3; j++) {
                for (int k = 0; k < 3; k++) {
                    for (int l = 0; l < 3; l++) {
                        if ((j != k) || (j == l)) {
                            dp[i][j][k] = (dp[i][j][k] + dp[i - 1][l][j]) % mod;
                        }
                    }
                }
            }
        }
        
        long count = 0;
        for (int j = 0; j < 3; j++) {
            for (int k = 0; k < 3; k++) {
                count = (count + dp[n][j][k]) % mod;
            }
        }
        
        return (int) count;
    }
}

Loading editor...