yokostan / Leetcode-Solutions

Doing exercise on Leetcode. Carry on!
0 stars 3 forks source link

Leetcode #276. Paint Fence #240

Open yokostan opened 5 years ago

yokostan commented 5 years ago

The crucial point here is to divide the case as whether i post will be painted the same as or different from the i-1 post. And the main part is to come with the recursive relationship.

class Solution {
    public int numWays(int n, int k) {
        if (n == 0) return 0;
        if (n == 1) return k;
        if (n == 2) return k*k;

        int[] dp = new int[n + 1];
        dp[0] = 0;
        dp[1] = k;
        dp[2] = k*k;

        for (int i = 3; i <= n; i++) {
            dp[i] = (dp[i - 1] + dp[i - 2]) * (k - 1);
        }

        return dp[n];
    }
}

reference: https://leetcode.com/problems/paint-fence/discuss/178010/The-only-solution-you-need-to-read