LeetCode 276. Paint Fence

本文详细解析了LeetCode中的第276题——涂色栅栏。题目要求给一个长度为n的栅栏涂色,每种颜色至少使用一次,求所有可能的涂色方案数。通过动态规划的方法,我们可以解决这个问题。文章深入浅出地介绍了动态规划的思路和实现代码,适合想要提升算法能力的开发者阅读。

#include <iostream>
#include <vector>
using namespace std;

/*
  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 colors.
  Return the total number of ways you can paint the fence. 
  Note: n and k are non-negative integers.
*/

/*
  It is better to use an example to illustrate the question.
  if n == 0, return 0 method.
  if n == 1, return k method (1 post can have k colors)
  
  // k-1 is the colors for second post different from the first one.
  // 1 is the color that  same as first post.
  if n == 2, return k * (k - 1) + k * 1. 

  // (k * 1 * (k-1) + k * (k - 1) * (k - 1)) is the choice that different from second post.
  // (k * (k-1) + k * 1) * 1, is the choice that same color as second post.
  if n == 3, return (k * 1 * (k-1) + k * (k - 1) * (k - 1)) + (k * (k-1) + k * 1) * 1 
*/
int numOfWays(int n, int k) {
  if(n == 0) return 0;
  if(n == 1) return k;
  int same_color = k;
  int different_color = k * (k - 1);
  for(int i = 3; i <= n; ++i) {
    int tmp = different_color;
    different_color = different_color * (k-1) + same_color * (k-1);
    same_color = tmp * 1;
  }
  return different_color + same_color;
}

int main(void) {
  cout << numOfWays(3, 2) << endl;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值