zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    python爬虫循环导入MySql数据库
    以洛谷P2661信息传递为例总结找环的常见的几种方法
    CF1339E-Perfect Triples (打表找规律)
    CF1339D-Edge Weight Assignment (dfs)
    CF1335E2-Three Blocks Palindrome (hard version) (二分+双指针)
    CF1327D-Infinite Path (循环置换)
    洛谷P3178 [HAOI2015]树上操作 (树链剖分)
    洛谷P2590 [ZJOI2008]树的统计 (树链剖分)
    洛谷P3833 [SHOI2012]魔法树 (树链剖分)
    树链剖分板子
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8561697.html
Copyright © 2011-2022 走看看