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: Red, Yellow 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
思路:记忆化递归,这才是面试的时候能够表现出来的;dfs(n, a0, b0, c0, dp) 代表的物理意义是:面对第n行row,我的当前层的颜色是a0,b0,c0的情况下,我能够选择的种类有多少;然后用三个for循环,下一层如果是a, b, c 那么就有关系;a != a0, b != b0 && b != a, c != c0 && c != b; 这一层的选择种类就是: ans += dfs(n -1, a, b, c, dp); 写法:相当于,最后一层是0,0,0,从第0层开始,计算到底端,再往上走;
class Solution {
private int MOD = 1000000007;
public int numOfWays(int n) {
if(n <= 0) return 0;
int[][][][] cache = new int[n + 1][4][4][4];
return dfs(0, 0, 0, 0, cache);
}
private int dfs(int row, int a0, int b0, int c0, int[][][][] cache) {
// 递归到最底层,就是输入的a0, b0, c0三种颜色组合了;以这三个颜色往上走;
if(row == cache.length - 1) {
return 1;
}
if(cache[row][a0][b0][c0] != 0) {
return cache[row][a0][b0][c0];
}
int[] colors = {1,2,3};
int value = 0;
for(int a : colors) {
if(a == a0) {
continue;
}
for(int b: colors) {
if(b == b0 || b == a) {
continue;
}
for(int c: colors) {
if(c == c0 || c == b) {
continue;
}
value = (value % MOD + dfs(row + 1, a, b, c, cache) % MOD) % MOD;
}
}
}
cache[row][a0][b0][c0] = value;
return cache[row][a0][b0][c0];
}
}