返回介绍

solution / 0200-0299 / 0276.Paint Fence / README_EN

发布于 2024-06-17 01:04:02 字数 3269 浏览 0 评论 0 收藏 0

276. Paint Fence

中文文档

Description

You are painting a fence of n posts with k different colors. You must paint the posts following these rules:

  • Every post must be painted exactly one color.
  • There cannot be three or more consecutive posts with the same color.

Given the two integers n and k, return _the number of ways you can paint the fence_.

 

Example 1:

Input: n = 3, k = 2
Output: 6
Explanation: All the possibilities are shown.
Note that painting all the posts red or all the posts green is invalid because there cannot be three posts in a row with the same color.

Example 2:

Input: n = 1, k = 1
Output: 1

Example 3:

Input: n = 7, k = 2
Output: 42

 

Constraints:

  • 1 <= n <= 50
  • 1 <= k <= 105
  • The testcases are generated such that the answer is in the range [0, 231 - 1] for the given n and k.

Solutions

Solution 1

class Solution:
  def numWays(self, n: int, k: int) -> int:
    dp = [[0] * 2 for _ in range(n)]
    dp[0][0] = k
    for i in range(1, n):
      dp[i][0] = (dp[i - 1][0] + dp[i - 1][1]) * (k - 1)
      dp[i][1] = dp[i - 1][0]
    return sum(dp[-1])
class Solution {
  public int numWays(int n, int k) {
    int[][] dp = new int[n][2];
    dp[0][0] = k;
    for (int i = 1; i < n; ++i) {
      dp[i][0] = (dp[i - 1][0] + dp[i - 1][1]) * (k - 1);
      dp[i][1] = dp[i - 1][0];
    }
    return dp[n - 1][0] + dp[n - 1][1];
  }
}
class Solution {
public:
  int numWays(int n, int k) {
    vector<vector<int>> dp(n, vector<int>(2));
    dp[0][0] = k;
    for (int i = 1; i < n; ++i) {
      dp[i][0] = (dp[i - 1][0] + dp[i - 1][1]) * (k - 1);
      dp[i][1] = dp[i - 1][0];
    }
    return dp[n - 1][0] + dp[n - 1][1];
  }
};
func numWays(n int, k int) int {
  dp := make([][]int, n)
  for i := range dp {
    dp[i] = make([]int, 2)
  }
  dp[0][0] = k
  for i := 1; i < n; i++ {
    dp[i][0] = (dp[i-1][0] + dp[i-1][1]) * (k - 1)
    dp[i][1] = dp[i-1][0]
  }
  return dp[n-1][0] + dp[n-1][1]
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文