Leetcode-1420 生成数组

Leetcode 1420:生成数组(超详细的解法!!!) 给你三个整数 n、m 和 k 。下图描述的算法用于找出正整数数组中最大的元素。 请你生成一个具有下述属性的数组 arr : arr 中有 n 个整数。 1 <= arr[i] <= m 其中 (0 <= i < n) 。 将上面提到的算法应用于 arr ,search_cost 的值等于 k 。 返回上述条件下生成数组 arr 的 方法数 ,由于答案可能会很... 阅读详情

描述

给你三个整数 n、m 和 k 。下图描述的算法用于找出正整数数组中最大的元素。

func maxIn(arr []int) (int, int) {
    max_v := 0
    max_i := 0
    sc:=0
    for i:=0;i<len(arr);i++{
        if max_v < arr[i] {
            max_v = arr[i]
            max_i = i
            sc++
        }
    }
    return max_v, max_i
}

请你生成一个具有下述属性的数组 arr :

arr 中有 n 个整数。
1 <= arr[i] <= m 其中 (0 <= i < n) 。
将上面提到的算法应用于 arr ,search_cost 的值等于 k 。
返回上述条件下生成数组 arr 的 方法数 ,由于答案可能会很大,所以 必须 对 10^9 + 7 取余。

 

示例1

输入:n = 2, m = 3, k = 1
输出:6
解释:可能的数组分别为 [1, 1], [2, 1], [2, 2], [3, 1], [3, 2] [3, 3]

示例 2

输入:n = 5, m = 2, k = 3
输出:0
解释:没有数组可以满足上述条件

示例 3

输入:n = 9, m = 1, k = 1
输出:1
解释:可能的数组只有 [1, 1, 1, 1, 1, 1, 1, 1, 1]

示例 4

输入:n = 50, m = 100, k = 25
输出:34549172
解释:不要忘了对 1000000007 取余

示例 5

输入:n = 37, m = 17, k = 7
输出:418930126

提示

1 <= n <= 50
1 <= m <= 100
0 <= k <= n


来源:力扣(LeetCode)
链接:https:leetcode-cn.com/problems/build-array-where-you-can-find-the-maximum-exactly-k-comparisons
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法

// 关键元素的位置问题
// 按关键元素所在位置分类
// 状态变量:n,m,k

const mod =1e9+7


func numOfArrays(n int, m int, k int) int {
	// f[n][i][k]:n个元素,元素最大值i,search_cost为k的切片数量
	f := make([][][]int, n+1)
	for i:=0;i<n+1;i++{
		f[i] = make([][]int, m+1)
		for j:=0;j<m+1;j++{
			f[i][j] = make([]int, k+1)
		}
	}
	for n1:=1;n1<=n;n1++{
		for k1:=1;k1<=k;k1++{
			for i:=1;i<=m;i++{
				f[n1][i][k1] = i* f[n1-1][i][k1]
				for j:= 1; j<i;j++{
					f[n1][i][k1] += f[n1-1][j][k1-1]
				}
				if n1 == 1 && k1 == 1 {
					f[n1][i][k1] = 1
				}
				f[n1][i][k1] %= mod
			}
		}
	}
	res := 0
	for i:=1;i<=m;i++{
		res += f[n][i][k]
		res %= mod
	}
	return res
}

 

C++前缀和算法:1420生成数组 动态规划,日后完成。 阅读详情

相关推荐

华为IPD实战:从概念到发布的完整流程拆解(附各阶段关键文档模板)

本文深入拆解华为IPD(集成产品开发)从概念到发布的完整实战流程,涵盖概念、计划、开发验证及发布生命周期四大阶段。详细解析了各阶段的核心活动、关键产出与决策评审点,并提供了如《初始业务计划书》等关键文档模板框架,旨在帮助企业将IPD理论转化为可执行的操作指南,提升研发效率与产品成功率。

weixin_29212429的博客 525

1420. Build Array Where You Can Find The Maximum Exactly K Comparisons

Given three integersn,mandk. Consider the following algorithm to find the maximum element of an array of positive integers: You should build the array arr which has the following properties:...

Do not mess it up 473

MAX30102传感器实战:从寄存器配置到Arduino心率血氧监测

本文详细介绍了MAX30102传感器在Arduino平台上的实战应用,从寄存器配置到心率血氧监测的全过程。通过清晰的代码示例和实用技巧,帮助开发者快速实现脉搏血氧仪功能,包括I2C通信、FIFO数据处理及算法实现,适用于健康监测和可穿戴设备开发。

weixin_29182481的博客 511

Leetcode 1389:按既定顺序创建目标数组(超详细的解法!!!)

给你两个整数数组 nums 和 index。你需要按照以下规则创建目标数组: 目标数组 target 最初为空。 按从左到右的顺序依次读取 nums[i] 和 index[i],在 target 数组中的下标 index[i] 处插入值 nums[i] 。 重复上一步,直到在 nums 和 index 中都没有要读取的元素。 请你返回目标数组。 题目保证数字插入位置总是存在。 示例 1: 输入...

coordinate的博客 719

Allegro老鸟的20年效率秘籍:用YepEda Skill脚本实现PCB设计全流程自动化

本文分享了Allegro资深工程师20年效率秘籍,通过YepEda Skill脚本实现PCB设计全流程自动化。从封装建库到规则配置,再到DFM审核,YepEda Skill大幅提升设计效率,每天节省至少4小时重复劳动。文章详细解析了自动化工具链的核心功能,并提供了实战技巧和量化对比数据。

weixin_42546392的博客 238

Matlab信号处理

Matlab信号处理 需要安装的APP: Signal Analyzer app:提供一个可以在时域和频域可视化、测量、分析和比较信号的工具; Filter Builder和Filter Designer app:可以很方便通过下拉菜单和填写参数的方式来设计和分析数字滤波器; 对于小波分析,Matlab提供了: 1.Wavelet Signal Denoise app:利用离散小波变换对信号去噪; 2.Signal Multiresolution Analyzer app:对信号进行多分辨率的分析和可视化

Huichin_Min的博客 4398

leetcode-生成数组

 题目是LeetCode第185场周赛的第四题,链接:生成数组。具体描述见原题。  这道题是hard难度的,然后不出意料又是动态规划的题目,难点自然在于递推公式。定义dp[i][j][p]代表对于前i个数,最大的数为j,然后search cost为p时的符合条件的数组总数。那么对于前i个数且最大值为j、search cost为k的这种情况,又可以分为两种情况: 最大值j在位置1~i-1之间,则第...

JR_Chan的博客 387

KCP(快速可靠UDP)——用带宽换延迟的极致艺术

想象你是一个外卖平台的调度员。这就是KCP的本质——

本博客聚焦游戏开发技巧、创业实战心得及大学热门课程干货。这里既有技术深度,也有思维广度,无论你是开发者、创业者还是高校学子,都能在这里找到适合自己的成长之路! 202

LeetCode 生成数组

/** dp[n][k][m] 定义为:n个位置,k个search_cost,以m结尾的数组种类个数 由这个定义,可得初始化 dp[1][1][1...m] = 1 转移方程为:dp[n][k][m] = m*dp[n-1][k][m] + dp[n-1][k-1][m-1] + dp[n-1][k-1][m-2] + ... + dp[n-1][k-1][1] 由此最后结果:n个位置,k个se...

NLSQQ的博客 311

【论文解读】Baidu Apollo EM Motion Planner

系统顶层是一种多车道策略,通过并行计算车道级别轨迹来处理车道变更场景;在车道轨迹生成器内部,迭代的解决基于Frenet坐标的路径和速度规划;针对路径和速度规划问题,提出了动态规划与基于样条的二次规划相结合的方法,构造了一个可扩展且易于调整的框架,同时处理交通规则、障碍物决策和平滑度问题。该规划器可扩展至高速公路和城市低速驾驶场景。高精地图模块提供了任何人都可以访问的高精地图。感知和定位模块提供了动态环境中必要的信息。运动规划模块考虑生成一条安全平滑的轨迹再交由汽车的控制模块去执行。

xiewf的博客 6092

【车载以太网】【AVB/TSN】IEEE802.1Qav队列及转发协议

目录 一、概述 二、优先级排队算法 三、基于信用的流量整形算法 一、概述 IEEE 802.1Qav 队列及转发协议(Qav)针对不同数据流选择不同的传输选择算法来保障对时间敏感的 AV 数据流的实时传输。为了避免传统的异步以太网数据流量与 AVB 流量之间对网络资源的竞争,AVB 交换机内使用优先级排队算法和基于信用的流量整形算法实现数据流的调度。 二、优先级排队算法 优先级排队算法主要用于传统以太网数据流(BE, Best Effort)的调度传输,BE 流通过基于优先级...

专注汽车软件开发、AutoSAR、车载以太网、SOA、EE架构。 4687

LeetCode 1420. 生成数组

动态规划 + 计数DP

英雄哪里出来 1569

绿盾用户使用看图软件每次都需要把图片解密之后才能打开查看,怎么才能不用这么麻烦打开就能看

Win10专业版绿盾控制台7.0看图软件FastStone Image Viewer。

本博客,博文仅代表个人操作经验,不能完全解决你的问题,仅供参考,佛系回复。 1202

[LeetCode解题报告] 1420. 生成数组

一道我不会的dp题

liuliangcan的博客 170

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

LeetCode 1420题:动态规划解决生成数组问题

动态规划是解决复杂计数问题的有效方法,通过将问题分解为子问题并存储中间结果来提高效率。在算法设计中,状态定义和转移方程是关键,特别是处理多维约束时。LeetCode 1420题要求统计满足特定比较操作次数的数组数量,这涉及到数组长度、元素范围和操作次数三个维度。通过前缀和优化,可以将时间复杂度从O(n*m²*k)降低到O(n*m*k),显著提升性能。这类技术在数据库索引分析和算法性能评估中有广泛应用,是动态规划与工程实践结合的典型案例。

weixin_32175665的博客 273

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

LeetCode 1420题动态规划解法:生成特定比较次数的数组

动态规划是解决复杂计数问题的核心算法范式,其本质是通过状态定义和转移方程将问题分解为子问题。在数组生成类问题中,三维DP状态设计(位置、最大值、比较次数)能有效建模约束条件。前缀和优化技术可将O(n*m²*k)时间复杂度降为O(n*m*k),这是算法竞赛和工程实践中处理高维DP的常用手段。以LeetCode 1420题为例,该解法展示了如何统计满足特定比较次数的数组组合,这类技术在数据库查询优化和特征工程中有广泛应用。通过状态压缩和边界条件处理,算法能高效解决n=50,m=100,k=10等实际规模问题。

weixin_34101914的博客 178

深度学习工具包 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")

java开发做力扣,力扣hard——1420.生成数组(动态规划)

力扣第185场周赛最后一题生成数组,挺有意思的一道题先来看看题目题目解析:首先,此题给出的代码就是一个在数组中寻找最大值的代码其中的search_cost代表的就是在寻找过程中更新了几次最大值,也就是有多少对相邻的两个数是升序排列的。再看题目要求,结合刚才的分析,可以把题目抽象成:要求有多少个有n个整数、整数大小大于1小于m、有k对相邻的两个数是升序排列的数组的数量。解题思路:我们可以很快的想到一...

weixin_34184876的博客 314

Kimi2.5 LeetCode 1420.生成数组 public int numOfArrays(int n, int m, int k)

为了避免每次都对 `dp[i-1][1..j-1][c-1]` 求和,我们可以维护一个前缀和数组 `prefix[j][c]` 表示最大值不超过 `j` 且代价为 `c` 的所有方案数。// 情况2:新元素是最大值 j,那么之前最大值在 [1, j-1] 且代价为 c-1。1. 状态设计:`dp[i][j][c]` 表示长度为 `i`、最大值为 `j`、代价为 `c` 的方案数。- 前 `i-1` 个元素的最大值必须是 `[1, j-1]` 中的某个值。// 枚举最大值 j 从 1 到 m。

m0_37843156的博客 31

每日一道Leetcode- 1420. 生成数组 【动态规划】

看别人的解法,强大! class Solution: def numOfArrays(self, n: int, m: int, k: int) -> int: # 长度为n 数组中每个元素范围:[1,m] # 使得找到最大值的搜索代价小于k # 生成这样的数组 相当于最大值要在数组中的前k个 # dp[n][i][k] n:长度 i:m的可选值 k:serach_cost def cal(n,i,k): .

weixin_41041275的博客 161

LeetCode题解(1420):生成数组(Python)

题目:原题链接(困难) 标签:动态规划 解法 时间复杂度 空间复杂度 执行用时 Ans 1 (Python) O(50×50×100)O(50×50×100)O(50×50×100) O(50×50×100)O(50×50×100)O(50×50×100) 120ms (94.44%) Ans 2 (Python) Ans 3 (Python) 解法一: MOD = 10 ** 9 + 7 # 定义状态矩阵:dp[n][k][m] MAX_N, MAX_M, MAX

长行 461

Leetcode 1420. 生成数组(DAY 58) ---- 动态规划学习期(困难的题确实不好做 先去吃饭回来看能不能再做一道)

原题题目 代码实现(首刷大部分看解小部分自解) int numOfArrays(int n, int m, int k){ long dp[n+1][k+1][m+1],numbers,cost,tempnumber,i,mod = 1000000007,sum = 0; memset(dp,0,sizeof(dp)); for(numbers=1;numbers<=n;numbers++) { for(cost=1;cost<=k;cost

Love 6's Private Blog 320

1420. 生成数组(Hard)

题目链接

newCraftsman的博客 199

【数据结构】leetcode数据结构刷题总结

leetcode上的数据结构刷题总结。

日拱一卒,功不唐捐。 580

leetcode 185场周赛

1418.点菜展示表 static int cmp(string a, string b) { return atoi(a.c_str()) < atoi(b.c_str()); } vector<vector<string>> displayTable(vector<vector<string>>& orders)...

qq_35752161的博客 143

力扣OJ(1401-1500)

目录 1414. 和为 K 的最少斐波那契数字数目 1420. 生成数组 1424. 对角线遍历 II 1461. 检查一个字符串是否包含所有长度为 K 的二进制子串 1496. 判断路径是否相交 1502. 判断能否形成等差数列 1503. 所有蚂蚁掉下来前的最后一刻 1504. 统计全 1 子矩形 1414. 和为 K 的最少斐波那契数字数目 给你数字 k,请你返回和为k的斐波那契数字的最少数目,其中,每个斐波那契数字都可以被使用多次。 斐波那契数字定义为: F1 ...

nameofcsdn的博客 3864
上一篇: Leetcode-19 秋叶收藏集
下一篇: Leetcode-650 只有两个键的键盘
vectorX
博客等级 码龄11年 37粉丝 21原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值