276. Paint Fence篱笆涂色

[抄题]:

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.

 [暴力解法]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

可以2个柱子颜色相同,则起点从2开始, 之前的所有情况,包括0 和 1 都要分别列出来写

[思维问题]:

列了几步以后觉得列不完,没思路:从小到大,反正只有相同、不相同两种情况,分情况讨论就行了

[一句话思路]:

第三根柱子开始有讨论余地,从此开始进行分类讨论。

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. 定义了temp,忘记用了。要注意temp

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

列不出来就分情况讨论

[复杂度]:Time complexity: O(n) Space complexity: O(1) 没有新建数组、链表,就是四则运算时,空间为1

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

public class Solution {
    /**
     * @param n: non-negative integer, n posts
     * @param k: non-negative integer, k colors
     * @return: an integer, the total number of ways
     */
    public int numWays(int n, int k) {
        //corner case: n = 0 or 1
        if (n == 0 || k == 0) {
            return 0;
        }
        if (n == 1) {
            return k;
        }
        //ini 0,1th
        int sameColors = k;
        int differentColors = k * (k - 1);
        //getsum from 2 to <n
        for (int i = 2; i < n; i++) {
            int temp = differentColors;
            differentColors = (temp + sameColors) * (k - 1);
            sameColors = temp;
        }
        //answer n- 1
        return differentColors + sameColors;
    }
}
View Code

 

posted @ 2018-03-13 20:36  苗妙苗  阅读(261)  评论(0编辑  收藏  举报