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 colors: Red, Yellow, or Green while making sure that no two adjacent cells have the same color (i.e., no two cells that share vertical or horizontal sides have the same color).
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.
Model the problem using two states for each row: the number of ways to paint the row with two color patterns (type1: all three colors different, type2: two colors same, but no adjacent same color). Use DP to propagate the count for each row.
classSolution {
public:int numOfWays(int n) {
int MOD =1e9+7;
long a =6, b =6;
for (int i =2; i <= n; ++i) {
long a_new = (2*a +2*b) % MOD;
long b_new = (2*a +3*b) % MOD;
a = a_new; b = b_new;
}
return (a + b) % MOD;
}
};
1
2
3
4
5
6
7
8
funcnumOfWays(nint) int {
mod:= int(1e9+7)
a, b:=6, 6fori:=2; i<=n; i++ {
a, b = (2*a+2*b)%mod, (2*a+3*b)%mod }
return (a+b)%mod}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
publicintnumOfWays(int n) {
int MOD = 1_000_000_007;
long a = 6, b = 6;
for (int i = 2; i <= n; ++i) {
long a_new = (2*a + 2*b) % MOD;
long b_new = (2*a + 3*b) % MOD;
a = a_new; b = b_new;
}
return (int)((a + b) % MOD);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funnumOfWays(n: Int): Int {
val MOD = 1_000_000_007
var a = 6L; var b = 6Lfor (i in2..n) {
val aNew = (2*a + 2*b) % MOD
val bNew = (2*a + 3*b) % MOD
a = aNew; b = bNew
}
return ((a + b) % MOD).toInt()
}
}
1
2
3
4
5
6
7
classSolution:
defnumOfWays(self, n: int) -> int:
MOD =10**9+7 a, b =6, 6for _ in range(2, n+1):
a, b = (2*a +2*b) % MOD, (2*a +3*b) % MOD
return (a + b) % MOD
1
2
3
4
5
6
7
8
9
10
11
12
13
impl Solution {
pubfnnum_of_ways(n: i32) -> i32 {
letmut a =6i64;
letmut b =6i64;
let m =1_000_000_007i64;
for _ in2..=n {
let a_new = (2*a +2*b) % m;
let b_new = (2*a +3*b) % m;
a = a_new; b = b_new;
}
((a + b) % m) asi32 }
}