[LeetCode] Paint Fence

本文介绍了一种动态规划算法,用于解决给定长度和颜色数量的围栏涂色问题,确保相邻围栏颜色不同,详细解释了算法原理及其实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

动态规划,可以使用滚动数组节省空间。dp[i][j][0]表示第i个fence的颜色为j,同时与第i-1个fence颜色不同的方案数;dp[i][j][1]表示第i个fence的颜色为j,同时与第i-1个fence颜色相同的方案数。

 1 class Solution {
 2 public:
 3     int numWays(int n, int k) {
 4         if (n == 0 || k == 0) return 0;
 5         if (n == 1) return k;
 6         int dp[2][k][2];
 7         for (int j = 0; j < k; ++j) {
 8             dp[0][j][0] = 1;
 9             dp[0][j][1] = 0;
10         }
11         for (int i = 1; i < n; ++i) {
12             int sum = 0;
13             for (int j = 0; j < k; ++j) {
14                 sum += (dp[(i-1)%2][j][0] + dp[(i-1)%2][j][1]);
15             }
16             for (int j = 0; j < k; ++j) {
17                 dp[i%2][j][1] = dp[(i-1)%2][j][0];
18                 dp[i%2][j][0] = sum - dp[(i-1)%2][j][0] - dp[(i-1)%2][j][1];
19             }
20         }
21         int res = 0;
22         for (int i = 0; i < k; ++i) {
23             res += dp[(n-1)%2][i][0] + dp[(n-1)%2][i][1];
24         }
25         return res;
26     }
27 };

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值