zoukankan      html  css  js  c++  java
  • Paint Fence -- LeetCode

    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.

    思路:DP。

    设p(i)表示从第一张海报到第i张海报的情况数。

    初始情况:p(0) = 0,p(1) = k。

    当n=2时,有两种情况:1)第二张海报的颜色与第一张不同,一共k * (k - 1)种情况;2)两张海报的颜色一样,一共k种情况。所以p(2) = k + k* (k - 1).

    当n>2时,假设当前是第i张海报,此时有两种情况:1)第i张海报与前一张的颜色不同,一共是p(i - 1) * (k - 1)种情况; 2) 第i张海报与前一张的颜色一样,一共是p(i-2) * (k - 1)种情况。

    所以p(i) = p(i-2)*(k-1) + p(i-1)*(k-1).

    在实现时,我们并不需要用数组来记录所有的结果,我们只需要p(i-2)和p(i-1)的值,因此可以用变量slow来记录p(i-2)的值,用fast来记录p(i-1)的值。

     

     1 class Solution {
     2 public:
     3     int numWays(int n, int k) {
     4         if (n == 0) return n;
     5         if (n == 1) return k;
     6         int slow = k;
     7         int fast = slow + slow * (k - 1);
     8         for (int i = 3; i <= n; i++) {
     9             int cur = slow * (k - 1) + fast * (k - 1);
    10             slow = fast;
    11             fast = cur;
    12         }
    13         return fast;
    14     }
    15 };
  • 相关阅读:
    关于httpd服务的安装、配置
    时间同步ntp服务的安装与配置(作为客户端的配置
    通过挂载系统光盘搭建本地yum仓库的方法
    linux系统的初化始配置(包括网络,主机名,关闭firewalld与selinux)
    Linux下GNOME桌面的安装
    Java面试题汇总
    无敌存储过程分页使用
    正则表达式
    函数
    杂货
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5767774.html
Copyright © 2011-2022 走看看