zoukankan      html  css  js  c++  java
  • [LintCode] 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.

    Notice

    n and k are non-negative integers.

    Example
    Given n=3, k=2 return 6

    post 1, post 2, post 3
    way1 0 0 1
    way2 0 1 0
    way3 0 1 1
    way4 1 0 0
    way5 1 0 1
    way6 1 1 0

    LeetCode上的原题,请参见我之前的博客Paint Fence

    class Solution {
    public:
        /**
         * @param n non-negative integer, n posts
         * @param k non-negative integer, k colors
         * @return an integer, the total number of ways
         */
        int numWays(int n, int k) {
            int same = 0, diff = k;
            for (int i = 2; i <= n; ++i) {
                int t = diff;
                diff = (same + diff) * (k - 1);
                same = t;
            }
            return same + diff;
        }
    };
  • 相关阅读:
    3
    正确的消费理念和方式
    2
    1
    善待精力,保持体力,保持热情
    为什么不从今天开始呢?
    c++中的新成员
    函数重载分析下
    函数重载分析上
    函数参数的扩展
  • 原文地址:https://www.cnblogs.com/grandyang/p/5448516.html
Copyright © 2011-2022 走看看