[LeetCode(Java)-276]フェンスのカラーリング



Fence Coloring



記事のディレクトリ

class Solution { public int numWays(int n, int k) { int[] f = new int[n+1] // Number of schemes table, f[3] represents the number of schemes to color 3 fences for (int i = 1 i <= n i++) { if (i == 1) { f[i] = k } else if (i == 2) { f[i] = k * k } else { // If the nth fence is different from the previous one, there are f[i-1] * (k-1) number of schemes // If the nth fence is the same color as the previous one, then the previous one and the previous one cannot be the same color, so f[i-2] * (k-1) // The total number of color schemes on the nth fence: f[i-1] * (k-1) + f[i-2] * (k-1) f[i] = f[i - 1] * (k - 1) + f[i - 2] * (k - 1) } } return f[n] } }