• 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
  • 相关阅读:
    一文让你快速入门pytest框架
    Python classmethod 修饰符
    python三种导入模块的方法
    18 | 眼前一亮:带你玩转GUI自动化的测试报告
    20193103《Python程序设计》实验二报告
    20193103陈柏维《Python程序设计》实验四报告
    20193103《Python程序设计》实验三报告
    20193103陈柏维《Python程序设计》实验一报告
    一种有效的编程思路
    一些希望实现的项目
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8561697.html
Copyright © 2020-2023  润新知