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.

Show Company Tags Show Tags Show Similar Problems

Solution

public class Solution {
    public int numWays(int n, int k) {
        if(k == 0 || n == 0) return 0;
        int non = k; // how many ways to paint so far if the current one do not have adjacent same color
        int adj = 0; // how many ways to paint so far if the current one have adjacent same color

        for(int i = 1; i < n; i++) {
            int newNon = non * (k - 1) + adj * (k - 1);
            int newAdj = non * 1;
            non = newNon;
            adj = newAdj;
        }

        return non + adj;
    }
}

results matching ""

    No results matching ""