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.
Note:?n and k are non-negative integers.

涂柵欄條最多兩個(gè)顏色在一起。艾瑪, 鬧心, 二刷看答案竟然還要想一會(huì)兒!!!尼瑪啊?

當(dāng)然這道題得用動(dòng)態(tài)規(guī)劃, 將1,2柵欄條相同顏色和不同顏色區(qū)分開, 分別計(jì)算可能性, 返回總和。還要考慮異常條件 沒有柵欄和僅有一個(gè)柵欄的情況。

空間復(fù)雜度O(2n), 根據(jù)規(guī)則可以發(fā)現(xiàn)只要另個(gè)變量O(2) 就可以做到。修改代碼。

public int numWays(int n, int k) {
? ? ? if(n == 0){
? ? ? ? ? ?return 0;
? ? ? }
? ? ? if(n == 1){
? ? ? ? ? ? return k;
? ? ? }
? ? ? int[] dp_same = new int[n];
? ? ? int[] dp_diff = new int[n];
? ? ? dp_same[0] = dp_same[1] = k;
? ? ? dp_diff[0] = k;
? ? ? dp_diff[1] = k*(k-1);
? ? ? for(int i = 2; i < n; i++ ){
? ? ? ? ? ? dp_same[i] = dp_diff[i-1];
? ? ? ? ? ? dp_diff[i] = (k - 1)*(dp_diff[i-1] + dp_same[i-1]);
? ? ? }
? ? ? return dp_diff[n-1] + dp_same[n-1];
}

public int numWays(int n, int k) {
? ? ? if(n == 0){
? ? ? ? ? ?return 0;
? ? ? }
? ? ?if(n == 1){
? ? ? ? ? ? return k;
? ? ?}
? ? ?int same = k;
? ? ?int diff = k * (k-1);
? ? ?for(int i = 2; i < n; i++){
? ? ? ? ? int temp = diff;
? ? ? ? ? diff = (same+diff)*(k-1);
? ? ? ? ? same = temp;
? ? ?}
? ? ?return same + diff;
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,766評(píng)論 0 33
  • There is a fence with n posts, each post can be painted w...
    Jeanz閱讀 228評(píng)論 0 0
  • 276- Paint Fence**My SubmissionsQuestionEditorial Solutio...
    番茄曉蛋閱讀 317評(píng)論 0 0
  • There is a fence with n posts, each post can be painted w...
    HalcyonMoon閱讀 179評(píng)論 0 0
  • 文|米格格 漆黑的影院里,仿佛一個(gè)人的包場(chǎng),《致我們終將逝去的青春》中陳孝正與張開的經(jīng)典話語點(diǎn)亮了整部電影。幕布上...
    米格格閱讀 639評(píng)論 4 18