[Leetcode] 276. Paint Fence 解题报告

来源:互联网 发布:中国人口普查数据 编辑:程序博客网 时间:2024/06/05 00:46

题目

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.

思路

这是一道简单的动态规划题目。在染一个柱子的时候,要考虑是否和上一个柱子的颜色相同,有两种方案:1)如果和上一个柱子染同一种颜色,那么取决于上一个柱子有多少种和上上个柱子不同的染色方案;2)如果染和上一个不同的颜色,那么染色方案就有(k - 1) * (之前总共有多少种方案)。由于状态转移方程中dp[i]只和前两个状态有关,所以可以将空间复杂度降低到O(1),时间复杂度则是最优的O(n)。

代码

class Solution {public:    int numWays(int n, int k) {        if(n == 0 || k == 0 || (k == 1 && n > 2)) {            return 0;        }        int same = 0, diff = k, total = k;        for(int i = 2; i <= n; ++i) {            same = diff;                // the i-th is the same as the (i-1)-th            diff = (k - 1) * total;     // the i-th is different from the (i-1)-th            total = same + diff;        }        return total;    }};

原创粉丝点击