★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-xordmjaw-ky.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
There is a fence with n posts, each post can be painted with one of the k colors.git
You have to paint all the posts such that no more than two adjacent fence posts have the same color.github
Return the total number of ways you can paint the fence.微信
Note:post
n and k are non-negative integers.spa
有一個有N根柱子的柵欄,每根柱子均可以塗上一種K顏色。 code
你必須把全部的柱子都刷上油漆,這樣兩個相鄰的柵欄柱子就不會有相同的顏色。 htm
返回能夠繪製圍欄的方法總數。 blog
注:get
n和k是非負整數。
Solution:
1 class Solution { 2 func numWays(_ n:Int,_ k:Int) -> Int { 3 if n == 0 {return 0} 4 var same:Int = 0 5 var diff:Int = k 6 for i in 2...n 7 { 8 var t:Int = diff 9 diff = (same + diff) * (k - 1) 10 same = t 11 } 12 return same + diff 13 } 14 }