zoukankan      html  css  js  c++  java
  • LeetCode 276. Paint Fence

    原题链接在这里:https://leetcode.com/problems/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.

    题解:

    base case n == 1, 那么有k种图法. n==2时,若选择相同图法,有k种. 若不同图法,有k*(k-1)种方法,总共有sameColorLastTwo + diffColorLastTwo种方法。

    DP时,当到了 i 时 有两种选择,第一种 i 和 i-1不同色,那么有 i-1的总共方法 * (k-1), 就是(sameColorLastTwo + diffColorLastTwo) * (k-1).

    第二种用相同色,那么 i -1 和 i-2 必须用不同色, 就是i-1的diffColorLastTwo.

    最后返回两种方法的和diffColorLastTwo + sameColorLastTwo.

    注意check corner case, e.g. n == 0, return 0. k == 0, return 0.

    Time Complexity: O(n). Space: O(1).                   

    AC Java:

     1 public class Solution {
     2     public int numWays(int n, int k) {
     3         if(n<=0 || k<=0){
     4             return 0;
     5         }
     6         if(n == 1){
     7             return k;
     8         }
     9         int sameColorLastTwo = k;
    10         int diffColorLastTwo = k*(k-1);
    11         for(int i = 3; i<=n; i++){
    12             int temp = diffColorLastTwo;
    13             diffColorLastTwo = (sameColorLastTwo + diffColorLastTwo) * (k-1);
    14             sameColorLastTwo = temp;
    15         }
    16         return diffColorLastTwo + sameColorLastTwo;
    17     }
    18 }

    类似Paint HouseHouse Robber.

  • 相关阅读:
    poj3660 最短路/拓扑序
    poj1502 最短路
    poj3259 最短路判环
    poj1680 最短路判环
    一些自己常用的cdn
    bower
    vuejs点滴
    jquery的ajax
    jquery点滴
    githubpage+hexo构建自己的个人博客
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/5244046.html
Copyright © 2011-2022 走看看