LeetCode 60 排列序列

【困难】力扣算法题解析LeetCode60:排列序列 本文提出了一种高效求解第k个排列的数学方法,避免枚举所有排列。核心思路是逐位确定数字:预处理阶乘值,初始化可用数字列表,通过计算索引k/(m-1)!确定当前位数字,移除已用数字并更新k为余数,直至构建完整排列。Java实现利用阶乘数组和动态调整的可用数字列表,时间复杂度O(n²),空间复杂度O(n)。示例展示了n=3时第3个排列为"213"的计算过程,适用于n≤9的场景。该方法显著优化了传统回溯法的性能,适用于大规模排列查询。 阅读详情

原文地址:https://leileiluoluo.com/posts/leetcode-permutation-sequence.html

1 题目描述
我们知道集合[1,2,3,...,n]共包含n!个排列。以n=3为例,其有序全排列如下。
"123"
"132"
"213"
"231"
"312"
"321"
本题给定n,求其有序全排列中的第k个。
注:n介于区间[1,9],k介于区间[1,n!]。

例子1:
输入:n = 3, k = 3
输出:"213"

例子2:
输入:n = 4, k = 9
输出:"2314"

题目出处:
https://leetcode.com/problems/permutation-sequence/

2 解决思路
首先根据k找到需要计算的最小子序列,假定找到的该子序列的长度为i,针对该序列分别将第[0,i-1]个元素至于头部的序列共有i*(i-1)!个全排列。所以根据该规律,对于给定的k,即可计算出第几个元素需至于头部,然后将k重置为余数,再对其子序列递归计算结果。

3 golang实现代码
https://github.com/olzhy/leetcode/blob/master/60_Permutation_Sequence/test.go

func factorial(i int) int {  
    f := 1  
    for ; i >= 1; i-- {  
        f *= i  
    }  
    return f  
}  
  
func getPermutaion(s string, k int) string {  
    i := len(s)  
    if 1 == i {  
        return s  
    }  
    factorial := factorial(i)  
    nextFactorial := factorial / i  
    if k <= nextFactorial {  
        return s[:1] + getPermutaion(s[1:], k)  
    }  
    c, k := (k-1)/nextFactorial, (k-1)%nextFactorial+1  
    if c > 0 {  
        s = string(s[c]) + s[:c] + s[c+1:]  
    }  
    return getPermutaion(s, k)  
}  
  
func getPermutation(n int, k int) string {  
    s := ""  
    for i := 1; i <= n; i++ {  
        s += strconv.Itoa(i)  
    }  
    return getPermutaion(s, k)  
}  

 

【LeetCode】60. 排列序列 这是一个基于数学原理的优雅解法,通过计算每个位置的数字,避免了生成所有排列的开销。核心思想是利用阶乘系统来定位每个位置的数字。使用预计算的阶乘数组代替递归使用正向循环代替while循环保持了原有的算法逻辑,但提高了效率。 阅读详情

相关推荐

OLLAMA_HOST环境变量设置全攻略:从127.0.0.1到局域网共享的完整配置

本文详细解析了OLLAMA_HOST环境变量的核心作用与配置方法,指导用户如何将Ollama服务从仅限本机访问(127.0.0.1)扩展到局域网共享。文章涵盖了macOS、Linux、Windows三大平台的实战配置步骤,并提供了安全加固、性能优化及常见故障排查方案,是解决多设备协作访问本地AI模型的完整指南。

weixin_28455801的博客 1896

leetcode:60. 排列序列

如上图,n = 4 ,k = 10,要找的是第 10 个。我们把数字都放到 nums 数组[1,2,3,4],索引 0 对应数字 1,有一个错位,所以把 k 减 1 处理。现在,剩下 3 个数字,[1, 3, 4],继续分组,如下图,更新一下 k,看看落入哪一组,重复上述步骤,确定出下一个数字,直到确定完 n 个数字。的取整,等于索引 1,对应nums数组的2,因此,确定了第一个数字2。事实上,我们不必求出所有的全排列。对于给定的n和k,我们不妨从左往右确定第k个排列中的每一个位置上的元素到底是什么。...

OceanStar的博客 420

CCS TMSC6748 报错Error connecting to the target: (Error -600 @ 0x0)

CCS TMSC6748 报错Error connecting to the target:(Error -600@ 0x0)

AS_the_deer1717的博客 6636

leetcode60:排列序列

无

Xi1yang的博客 188

借助OSS搭建在线教育视频课程分享网站-阿里云的课程体验和记录

阿里云的《搭建在线教育网站》免费课程里面讲的啥,我点进去看了看

LegendNoTitle的博客 3023

嵌入式开发实战:如何用cJSON库在STM32上实现轻量级JSON通信(附完整代码)

本文详细介绍了如何在STM32嵌入式系统中使用cJSON库实现高效的JSON通信方案。针对嵌入式环境的内存限制,提供了内存优化策略、cJSON库的深度定制方法以及完整的通信流程实现代码,帮助开发者解决JSON解析效率低下和跨平台兼容性等核心挑战。

star5的专栏 471

LeetCode 60. 排列序列

组合数学

英雄哪里出来 1426

零基础做完YOLOv8船只检测系统:HRSC2016数据集 + 完整UI,稳过答辩

亲爱的同学,通过这篇教程,你已经掌握了“基于YOLOv8的HRSC2016微小船只检测系统”从数据集处理、模型训练到Tkinter界面开发的全流程。这个课题既贴合“海事智能化”的产业战略,又涵盖了“目标检测、深度学习、界面开发”等多个毕设评分点,非常适合作为计算机或海事工程专业的毕业设计。在实践中,你可能会遇到“海面背景复杂导致船只漏检”“微小船只识别精度不足”“UI与模型推理同步卡顿”等挑战——别担心,这些都是技术成长的必经之路。

FJN110的博客 108

Leetcode.60 排列序列

回溯问题

感觉画质不如...原神的博客 372

防护装备穿戴检查:基于YOLOv8与UI界面的深度学习应用

通过结合YOLOv8模型与UI界面,本系统实现了防护装备穿戴检查的自动化。该系统能够快速识别工作人员是否正确佩戴了所需的防护装备,帮助提高安全管理水平。未来,随着技术的发展,防护装备穿戴检查系统将在更多领域得到应用,如工业现场、建筑工地等,实现更加精确和高效的实时监控。

YOLO 354

00 — Intel xe SVM 内核实现精读系列专栏导读

本文系统介绍了Intel Xe GPU的共享虚拟内存(SVM)实现机制。第一部分通过概念地图阐述SVM的六个核心概念及其关系;第二部分通过三个测试用例解析SVM关键功能:fault生命周期验证、madvise与VRAM迁移、跨GPU一致性;第三部分深入内核实现,包括初始化/销毁流程、Page Fault处理、MMU Notifier失效路径、异步垃圾回收、VRAM迁移机制、madvise实现原理,以及与ROCm SVM的对比。文章建议按功能模块顺序学习,从基本概念到测试用例,再深入内核实现细节,最后对比不同

图形/计算GPU的驱动与虚拟化技术分享园地 1667

Leetcode 第60排列序列两种解法

给出集合 [1,2,3,…,n],其所有元素共有 n! 种排列。 按大小顺序列出所有排列情况,并一一标记,当 n = 3 时, 所有排列如下: “123” “132” “213” “231” “312” “321” 给定 n 和 k,返回第 k 个排列。 示例 1: 输入:n = 3, k = 3 输出:“213” 示例 2: 输入:n = 4, k = 9 输出:“2314” 示例 3: 输入:n = 3, k = 1 输出:“123” 提示: 1 <= n <= 9 1 <= k &l

wtx517828126的博客 403

使用Microsoft Print to PDF进行编程:创建PDF文件的简单方法

Microsoft Print to PDF是一种内置于Windows操作系统中的功能,它允许我们通过打印操作将任何可打印的内容保存为PDF文件。然后,我们使用Microsoft Print to PDF打印机进行打印操作,并将输出文件保存为指定的PDF文件。使用Microsoft Print to PDF功能是一种方便且简单的方法来创建PDF文件,无论是在个人使用还是在企业开发中,它都可以提供良好的支持和灵活性。请注意,如果你使用的是其他编程语言,你可以根据相应的打印机接口或库来实现类似的功能。

TechSavant的博客 1635

力扣60 排列序列

力扣60 排列序列

dastatham的博客 460

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

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

LeetCode 60:排列序列

给定整数n和k,返回集合的k。直接生成所有排列再遍历到第k个的方法(时间复杂度O(n!)会因n≥10时阶乘爆炸而超时,因此需要的高效解法。

m0_75126572的博客 740

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

力扣(LeetCode)- 60. 排列序列(JavaScript)

力扣(LeetCode)- 60. 排列序列

小妖666个人笔记 420

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

力扣LeetCode #60 排列序列(GetPermutation)

- 题目描述 给出集合 [1,2,3,…,n],其所有元素共有 n! 种排列。按大小顺序列出所有排列情况,并一一标记,当 n = 3 时, 所有排列如下:“123”,“132”,“213”,“231”,“312”,“321”。 给定 n 和 k,返回第 k 个排列。 提示: 1 <= n <= 9 1 <= k <= n! 来源:LeetCode - 示例 示例 1: 输入:n = 3, k = 3 输出:“213” 示例 2: 输入:n = 4, k = 9 输出:“2314”

weixin_49155948的博客 419

LeetCode第60题_排列序列

给出集合,其所有元素共有n!种排列。按大小顺序列出所有排列情况,并一一标记,当n = 3给定n和k,返回第k个排列。

qq_40263592的博客 624

力扣60. 排列序列

class Solution { public String getPermutation(int n, int k) { char[] result = new char[n]; ArrayList<Integer> nums = new ArrayList<Integer>(); int[] factorial = new int[n]; factorial[0] = 1; for(int i

邓瞻的博客 225

Leetcode—60. 排列序列【困难】

运行结果 之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

Atticus的博客 786

力扣(LeetCode)60. 排列序列(C++)

【墨染】图解按位枚举。

墨染 629

力扣(LeetCode)60. 排列序列(2022.03.01)

给出集合 [1,2,3,…,n],其所有元素共有 n! 种排列。 按大小顺序列出所有排列情况,并一一标记,当 n = 3 时, 所有排列如下: “123” “132” “213” “231” “312” “321” 给定 n 和 k,返回第 k 个排列。 示例 1: 输入:n = 3, k = 3 输出:“213” 示例 2: 输入:n = 4, k = 9 输出:“2314” 示例 3: 输入:n = 3, k = 1 输出:“123” 提示: 1 <= n <= 9 1 <= k &l

ChaoYue_miku的博客 564

LeetCode-60题:排列序列解法二(原创)

算法实现精要:每个数字排列的下一个排列:就是从倒数第二个数字开始,往后找到比此数大的数字,两者进行交换,然后再将后面的数字进行排序即可,找不到的话序号向前推进。。。;算法实现最好能精益求精,不可浅尝辄止,温故而知新比做新的算法题可能收获更大;一定要有自己的原创算法思想,不能一味按照公式去套,那样的话就只是机械的应试刷题,没有自己的灵魂!没有自己的思想!LeetCode解题之前,一定不要看题解,看了就“破功”了!

it_fly的专栏 1302

leetcode60.排列序列

leetcode60.排列序列

qq_55713959的博客 495
上一篇: LeetCode 17 求电话号码的字母组合
下一篇: LeetCode 130 围起的区域
「已注销」
博客等级 码龄18年 2粉丝 10原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值