zoukankan      html  css  js  c++  java
  • Leetcode 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.

    Note:
    n and k are non-negative integers.


    解题思路:

    Dynamic programming

    Need two one-dimensional array dp1 and dp2,

    dp1[i] means the number of solutions when the color of last two fences (whose indexes are i-1,i-2) are same.

    dp2[i] means the number of solutions when the color of last two fences are different.

    So

    dp1[i]=dp2[i-1],

    dp2[i]=(k-1)(dp1[i-1]+dp2[i-1])=(k-1)(dp2[i-2]+dp2[i-1])

    Final result is dp1[n-1]+dp2[n-1].

    I use s (same) to stand for the number of ways when the last two fences are painted with the same color (the last element of dp1 in the above post) and d (different) with d1 and d2 to stand for the last two elements of dp2 in the above post.

    In each loop, dp1[i] = dp2[i-1] turns into s = d2 and dp2[i] = (k-1) * (dp2[i-2] + dp2[i-1]) becomes d2 = (k-1) * (d1 + d2). Moreover, d1 needs to be set to the oldd2, which is recorded in s. So we have d1 = s.

    Finally, the return value dp1[n-1] + dp2[n-1] is just s + d2.


    Java code:

    public int numWays(int n, int k) {
            if(n <=1 || k == 0) {
                return n*k;
            }
            int s = k, d1 = k, d2 = k*(k-1);
            for(int i = 2; i< n; i++) {
                s = d2;
                d2 = (k - 1) * (d1 + d2);
                d1 = s;
            }
            return s + d2;
        }

    Reference:

    1. https://leetcode.com/discuss/56146/dynamic-programming-c-o-n-time-o-1-space-0ms

    2. http://www.cnblogs.com/jcliBlogger/p/4783051.html

  • 相关阅读:
    TX1/TX2 Qt安装与配置
    Gsteramer 环境配置
    NVIDIA Jetson TX2刷机
    TX2之多线程读取视频及深度学习推理
    搭建USB摄像头转RTSP服务器的多种方法
    TX2 五种功耗模式
    NVIDIA TX1/TX2 对比
    tf.reduce_mean
    关闭tensorflow运行时的警告信息
    sudo: /usr/bin/sudo must be owned by uid 0 and have the setuid bit set
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4865691.html
Copyright © 2011-2022 走看看