1411. Number of Ways to Paint N × 3 Grid

You have a grid of size n x 3 and you want to paint each cell of the grid with exactly one of the three colours: RedYellow or Green while making sure that no two adjacent cells have the same colour (i.e no two cells that share vertical or horizontal sides have the same colour).

You are given n the number of rows of the grid.

Return the number of ways you can paint this grid. As the answer may grow large, the answer must be computed modulo 10^9 + 7.

 

Example 1:

Input: n = 1
Output: 12
Explanation: There are 12 possible way to paint the grid as shown:

Example 2:

Input: n = 2
Output: 54

Example 3:

Input: n = 3
Output: 246

Example 4:

Input: n = 7
Output: 106494

Example 5:

Input: n = 5000
Output: 30228214

 

Constraints:

  • n == grid.length
  • grid[i].length == 3
  • 1 <= n <= 5000

思路:用c1 c2 c3模拟一下就知道递推关系了

class Solution(object):
    def numOfWays(self, n):
        """
        :type n: int
        :rtype: int
        """
        mod = 10**9+7
        dp = [[6, 6] for _ in range(n)]
        for i in range(1, n):
            dp[i][0] = 2*dp[i-1][0] + 2*dp[i-1][1]
            dp[i][1] = 2*dp[i-1][0] + 3*dp[i-1][1]
            dp[i][0] %= mod
            dp[i][1] %= mod
        return sum(dp[n-1])%mod

s=Solution()
print(s.numOfWays(7))

 

你可能感兴趣的:(leetcode,DP)