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

思路:记忆化递归,这才是面试的时候能够表现出来的;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];
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值