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.

Example:

Input: n = 3, k = 2
Output: 6
Explanation: Take c1 as color 1, c2 as color 2. All possible ways are:   post1 post2 post3
----- ----- ----- -----
1 c1 c1 c2
  2 c1 c2 c1
  3 c1 c2 c2
  4 c2 c1 c1 
5 c2 c1 c2
  6 c2 c2 c1

思路是利用两个dp, 一个same, 一个dif, same[i] 表明i 跟i-1 两个fence 的颜色是一样的, 而dif[i] 表明i 跟 i-1 两个 fence的颜色是不一样的.

init:   same[0] = same[1] = k

dif[0] = k, dif[1] = k*(k-1)

same[i] = dif[i-1]

dif[i] = (same[i-1] + dif[i-1]) *(k-1)

Code    T: O(n)   S; O(1)  using rolling array

class Solution:
def numWays(self, n, k):
if n == 0: return 0
if n == 1: return k
same, dif = [0]*2, [0]*2
same[0] = same[1] = k
dif[0], dif[1] = k, k*(k-1)
for i in range(2, n):
same[i%2] = dif[i%2-1]
dif[i%2] = (k-1)*(same[i%2-1] + dif[i%2-1])
return same[(n-1)%2] + dif[(n-1)%2]

最新文章

  1. a byte of python(摘04)
  2. 使用Jil序列化JSON提升Asp.net web api 性能
  3. LINQ to SQL 语句(2)之 Select/Distinct
  4. sdut 2846 Remove Trees (二分 + 贪心)
  5. 用sql增、修改、删除字段
  6. Linux中yum手动安装、手动建立仓库文件夹关联实现关联包自动安装、yum相关命令使用
  7. iOS随机数-备
  8. 微信授权登陆接入第三方App(步骤总结)Android
  9. php汉字生成首字母
  10. Google开源的Deep-Learning项目word2vec
  11. 堆结构的优秀实现类----PriorityQueue优先队列
  12. java swing中Timer类的学习
  13. JavaSE | Lambda| Optional| Stream API
  14. Js实现Table动态添加一行的小例子
  15. java 线程(六)死锁
  16. putty登陆sourceforge.net(设置登录)
  17. (四)创建ROS程序包(就是软件包)
  18. Visual Studio Code compile error - launch.json must be configured...
  19. MongoDB单机, 主从, 分布式部署
  20. php基础系列:从用户登录处理程序学习mysql扩展基本操作

热门文章

  1. day_5.18_py总结
  2. PHP数组(数组正则表达式、数组、预定义数组)
  3. $(").each 和$.each
  4. SQL Server 2016 共享功能目录 不可修改
  5. {MySQL数据库初识}一 数据库概述 二 MySQL介绍 三 MySQL的下载安装、简单应用及目录介绍 四 root用户密码设置及忘记密码的解决方案 五 修改字符集编码 六 初识sql语句
  6. HDU 4699 - Editor - [对顶栈]
  7. MVC 实用架构设计(〇)——总体设计
  8. 分析java的堆栈信息 内存模型
  9. Django 的操作
  10. php安全