topic:
https://leetcode-cn.com/problems/number-of-ways-to-paint-n-x-3-grid/
You have an nx 3 grid grid, you need to color each grid with one of red, yellow, and green colors, and make sure that the adjacent grids are different in color (that is, grids with the same horizontal or vertical sides) Different colors).
Give you the number of rows in the grid graph n.
Please return the number of schemes that color grid. Since the answer may be very large, please return the result of the answer pair 10 ^ 9 + 7.
Example 1:
Input: n = 1
Output: 12
Explanation: There are 12 possible methods in total:
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
prompt:
n == grid.length
grid[i].length == 3
1 <= n <= 5000
Problem-solving ideas
- The use of mathematical methods is of course the most ecstatic. Let's use simple and crude methods.
- Obviously, as long as the conversion relationship between two adjacent lines is determined, the rest is iteration.
- There are only 12 patterns in the first line of handwriting. How much? Not much.
- Then exhaustively traverse to get all possible next-row patterns corresponding to these 12 patterns, and save them as the next dictionary.
- Save the pattern in the first line as a prev dictionary, the key is the pattern, and the value is initialized to 1, indicating that there is only one for each pattern in the first line.
- Then it traverses from the second line to the last line.
- At the beginning of each line, first store a dictionary curr to store the number of occurrences of each pattern.
- Then the point is coming!
- Traverse the key of prev, get all possible patterns from next [key], and update curr [next [key]].
- Note that when updating here, you need to accumulate prev [key] every time.
- At the end of each line, store the contents of curr into prev.
- The program finally sums the value of prev and modulo, and it's done.
Code
class Solution:
def numOfWays(self, n: int) -> int:
pattern = [
'RGB', 'RBG', 'RGR',
'RBR', 'GBR', 'GRB',
'GRG', 'GBG', 'BRG',
'BGR', 'BRB', 'BGB'
]
# - construct transfer dict
# - to handle adjacent rows
next = {}
for p1 in pattern:
next[p1] = []
for p2 in pattern:
is_ok = True
for i in range(3):
if p1[i] == p2[i]:
is_ok = False
break
if is_ok:
next[p1].append(p2)
# - first row
prev = {p:1 for p in pattern}
# - from second row
for i in range(n-1):
# - d is temp dict for current row
curr = {p:0 for p in pattern}
# - accumulate
for k,v in prev.items():
for x in next[k]:
curr[x] += v
# - update previous row
prev = copy.copy(curr)
return sum(prev.values()) % (10**9 + 7)