Leetcode——276.Paint Fence

算法-leetcode-剑指offer上的题很多 非常好的算法书,讲解很详细,有C++/JAVA/Python代码,很多都是leetcode上的题解,非常高清,值得下载,如果很好,请给好评,让更多人看到节约他们找资料的时间,谢谢。 立即下载

Description

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.

Solution

public class Solution {
    public int numWays(int n, int k) {
        // 当n=0时返回0
        int dp[] = {0, k , k*k, 0};
        if(n <= 2){
            return dp[n];
        }
        for(int i = 2; i < n; i++){
            // 递推式:第三根柱子要么根第一个柱子不是一个颜色,要么跟第二根柱子不是一个颜色
            dp[3] = (k - 1) * (dp[1] + dp[2]);
            dp[1] = dp[2];
            dp[2] = dp[3];
        }
        return dp[3];
    }
}

Note: n and k are non-negative integers
复杂度
时间 O(N) 空间 O(1)

思路
这种给定一个规则,计算有多少种结果的题目一般都是动态规划,因为我们可以从这个规则中得到递推式。根据题意,不能有超过连续两根柱子是一个颜色,也就意味着第三根柱子要么根第一个柱子不是一个颜色,要么跟第二根柱子不是一个颜色。如果不是同一个颜色,计算可能性的时候就要去掉之前的颜色,也就是k-1种可能性。假设dp[1]是第一根柱子及之前涂色的可能性数量,dp[2]是第二根柱子及之前涂色的可能性数量,则dp[3]=(k-1)*dp[1] + (k-1)*dp[2]。

递推式有了,下面再讨论下base情况,所有柱子中第一根涂色的方式有k中,第二根涂色的方式则是k*k,因为第二根柱子可以和第一根一样。

复杂度
时间 O(N) 空间 O(1)

另一种解释:
分析:

由题目可以知道,最多有两个相邻的栅栏可以涂相同的颜色。

则主要思想是,如果前两根栅栏颜色相同,则第三根栅栏的颜色不能跟前两根的栅栏颜色相同,若是前两根栅栏颜色不同,则第三根栅栏颜色随便涂。综合的思想就是,第三根栅栏或者与第一根栅栏的颜色不同,或者与第二根的栅栏颜色不同。(即,包括了,可以与前两个栅栏的颜色都不同,与第一根栅栏颜色不同时,可以与第二根相同,与第二根栅栏不同的时候可以与第一根相同)。

如果用num[0]表示第一根栅栏以及之前栅栏总共可以涂色的方法数量;(栅栏数量为i时的方法数量)

num[1]表示第二根栅栏以及之前栅栏总共可以涂色的方法数量;(栅栏数量为i+1时的方法数量)

num[ 2]表示第三根以及之前总共可以涂色的方法数量

num[3] = (k-1)*num[0] + (k-1)*num[1];

以此类推到n为止。

零基础玩转华为AP 4050DN-HD:FAT模式家庭无线网络配置实战 本文为零基础用户提供华为AP 4050DN-HD从FIT模式转换为FAT模式的完整实战教程。详细介绍了固件升级、模式转换以及配置家庭无线网络(包括路由、DHCP、Wi-Fi和NAT)的每一步操作,帮助用户将企业级瘦AP改造为高性能家庭胖AP,打造稳定可靠的家庭网络环境。 阅读详情

相关推荐

Unity 2021 LTS安装避坑指南:从下载到第一个3D项目的完整流程

本文提供了一份详尽的Unity 2021 LTS安装与首个3D项目创建指南。内容涵盖从Unity Hub下载、版本选择、模块安装避坑,到编辑器界面解析、创建旋转立方体脚本的完整流程,旨在帮助初学者快速搭建稳定开发环境并上手核心操作。

mango的博客 320

力扣(LeetCode)276. 栅栏涂色(2022.10.03)

解释:所有的可能涂色方案如上图所示。注意,全涂红或者全涂绿的方案属于无效方案,因为相邻的栅栏柱 最多连续两个 颜色相同。链接:https://leetcode.cn/problems/paint-fence。题目数据保证:对于输入的 n 和 k ,其答案在范围 [0, 2。给你两个整数 k 和 n ,返回所有有效的涂色 方案数。相邻的栅栏柱 最多连续两个 颜色相同。输入:n = 3, k = 2。输入:n = 1, k = 1。输入:n = 7, k = 2。来源:力扣(LeetCode)

ChaoYue_miku的博客 773

C# : 计算并输出这一天是这一年的第几天

C#之输入某年,然后输入某月,再输入某日,计算并输出这一天是这一年的第几天的功能算法

saitoDeng的博客 977

入门力扣自学笔记276 C++ (题目编号:874)

874. 模拟行走机器人

DK_Sorhic的博客 533

基于DSP28335的Matlab/Simulink代码生成实验七:A/D采样

实验七:讲解如何使用DSP的ADC模块,通过代码生成技术控制DSP进行电流采样,是后续实现电机闭环控制的重要环节。通过简单的实验来熟悉代码生成的过程。最终实现复杂算法代码自动生成,进行高性能电机控制!

m0_73869369的博客 4731

STM32F103 串口DMA + 空闲中断 实现不定长数据收发

文章目录1. 空闲中断1.1 uart_dma.c1.2 uart_dma.h1.3 main.c1.4 stm32f10x_it.c1.5 效果演示1.6 知识补充1.6.1 外设的基地址     DMA(Direct Memory Access,直接存储器访问) 是所有现代电脑的重要特色,它允许不同速度的硬件装置来沟通,而不需要依赖于 CPU 的大量中断负载。否则,CPU 需要从来源把每一片段的资料复制到暂存器,然后把它们再次写回到新的地方。在这个时间中,CPU

夏夜晚风_的博客 3万+

LeetCode第 276 题:栅栏涂色(C++)

276.栅栏涂色 dp[i]表示第i个栅栏的颜色方案数,根据题意,显然dp[1] = k, dp[2] = k*k。当i >= 3的时候: i和i-1颜色相同:dp[i] = dp[i-2]*(k-1),表示去掉i-2的颜色(将i-1和i连起来考虑,两者是相同的),还有k-1种可选 i和i-1颜色不同:dp[i] = dp[i-1]*(k-1),表示去掉i-1的颜色,还剩下k-1种颜色可选 求方案数,使用相加。 第一种的理解:假设颜色为1,2,3,4,如果i-2的颜色为1,因为i与i-1的颜色相

zj 968

core_analyzer分析c++程序内存占用

环境:centos; 进程:单进程多线程c++程序; 问题:1. 分析系统内存占用; 2. 分析ptmalloc内存空洞(bins上的空闲chunk的大小); 包括:1. 占用了很大内存的c++进程; 2. gcore(在进程不core dump的情况下生成core文件); 3. core_analyzer(分析gcor...

weixin_41644391的博客 4816

[LeetCode] Paint Fence

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. Re...

weixin_33757911的博客 156

Sigrity OptimizePI Best Capacitor Location Estimation模式如何评估电容最佳位置操作指导

Sigrity OptimizePI Best Capacitor Location Estimation模式用于前仿真分析,评估电容的最佳位置以获得最小回路电感,如何分析,以下图为例进行说明。IC devices,输入U*, A*, B*, Q*, P*,将所有这些字母开头的器件都识别为IC。Min设置为1(最少电容个数为1),max设置为28(最多电容个数为28)Capacitors 输入C*,将所有C开头的器件都识别为电容。Grid X设置为8,Grid Y也设置为8。

weixin_54787054的博客 385

基于分水岭分割进行肺癌诊断

近年来,肺癌的发病率和病死率均迅速上升,目前已居所有癌症之首。随着肺癌病人数量的增加,医生对肺部 CT 图像进行研判的工作量也增加了不少,在这种情况下难免工作效率降低甚至会出现误诊。为了帮助医生减少重复性工作,对肺部 CT 图像进行计算机辅助检测的技术就被广泛应用于对肺癌的诊断和治疗过程中。医学 CT 图像处理主要是研究医学图像中的器官和组织之间的关系,并进行病理性分析。

在职AI算法工程师,擅长计算机视觉,YOLO目标检测、分割等,擅长web、pyqt界面可视化,好内容持续更新中,来这里跟大家一起学习,共同进步 1574

514.Paint Fence-栅栏染色(容易题)

栅栏染色 题目我们有一个栅栏,它有n个柱子,现在要给柱子染色,有k种颜色可以染。 必须保证任意两个相邻的柱子颜色不同,求有多少种染色方案。注意事项 n和k都是非负整数 样例n = 3, k = 2, return 6 题解 本题中文翻译有误,应该是最多只能有两个相邻栅栏的颜色相同,而不是任意两个相邻栅栏的颜色都不同,可以参看下面的英文原文或者样例。 当有1个栅栏的时候,有k种;

三色旗飞扬 1556

华为od 面试八股文_前端_02_含答案

华为od 面试八股文_前端_02_含答案

MISAYAONE的博客 2014

LeetCode276 Paint Fence

。。。

李歇特冯-兹拜因巴哈的博客 273

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

【dp】leetcode 276. Paint Fence

【dp】leetcode 276. Paint Fence class Solution { public int numWays(int n, int k) { if(n==0||k==0) return 0; int[][][] dp = new int[n+1][k][2]; for(int j=0;j<k;j++){

独钓寒江雪 602

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

Leetcode 276. Paint Fence (Easy) (cpp)

Leetcode 276. Paint Fence (Easy) (cpp)

还是需要多学习!闷声大发财,这是坠吼的! 586

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

[leetcode] 276. Paint Fence @ python

原题 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 tot...

闲庭信步 766

[LeetCode276]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 num

MoM 1124

LeetCode 276. Paint Fence

#include #include 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 f

ActiveCoder的博客 387

Leetcode 276 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

夜色之浓,莫过于黎明前的黑暗。 990

[leetcode] 276. Paint Fence 解题报告

题目链接:https://leetcode.com/problems/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 adj...

小榕流光的专栏 5836

[Leetcode]276. Paint Fence

这题虽然是easy题,但其实,我个人还是不是特别的明白。所以还是记录一下 这题其实还是有很明显的dp特征的,只是这一题的限制或者说关系并不在于n和n - 1,而是在于n和n - 2。也就是前一面fence是怎么样并不直接影响当前这一堵fence。 先探讨一下这个递推式是怎么形成的。 只有两种情况需要考虑,首先是当前的fence和之前的fence颜色不同。如果说之前的fence颜色的总数是f...

chaochen1407的专栏 715

[leetcode 276] Paint Fence

Question: 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.

清空 3210

【Leetcode】276. Paint Fence

题目地址: https://leetcode.com/problems/paint-fence/ 给定nnn个柱子,可以染kkk种颜色,要求不能有连续超过两个相邻的柱子颜色一样,问有多少种染色方法。 参考https://blog.csdn.net/qq_46105170/article/details/110361142。代码如下: public class Solution { public int numWays(int n, int k) { if (k == 0) {

数学、算法爱好者的博客 303

Leetcode 276. 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 tota...

YIQI521的博客 313

[Leetcode] 276. 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. Re

魔豆(Magicbean)的博客 1015
上一篇: Leetcode——241. Different Ways to Add Parentheses
下一篇: 文章标题
路漫远吾求索
博客等级 码龄15年 434粉丝 162原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值