PU Paint Fence

Jan 01, 1970

There is a fence with n posts, each post can be painted with one of the k colors.

You have to paint all the posts such that no more than two adjacent fence posts have the same color.

Return the total number of ways you can paint the fence.

Note:
n and k are non-negative integers.

C Solution:

int numWays(int n, int k) {
    if (n == 0) return 0;
    if (n == 1) return k;
    int pre_same = k;
    int pre_diff = k * (k - 1);
    int i;
    for (i = 2; i < n; i++) {
        int _pre_same = pre_diff;
        pre_diff = (pre_diff + pre_same) * (k - 1);
        pre_same = _pre_same;
    }
    return pre_diff + pre_same;
}

Summary:

  • nothing to say.

LeetCode: 276. Paint Fence