LC60 Permutation Sequence
这道题目有两种做法,第一种是把排列一直列到第k个。另一种做法是利用康托编码,如果把n!个排列根据首个数字大小排列成n组,则每一组有(n-1)!个元素,求第k个排列,可以先令p=k/(n-1)! 求出第一个数字num[p].
然后递归做下去。更新数字k=k%(n-1)!,并在数组num中删除num[p]。如果把(n-1)!个排列根据第二个数字大小排列成(n-1)组,则每一组有(n-2)!个元素,求第k个排列,可以令p=k/(n-2)! 求出第二个数字num[p].
这样直到数组num中只有一个元素为止。
要特别注意,康托编码的第k个排列是从0开始数的。
1 class Solution { 2 public: 3 string getPermutation(int n, int k) { 4 string s=""; 5 if(n<=0||k<=0) 6 return s; 7 int tmp=1; 8 string str(n,'0'); 9 for(int i=1;i<=n;i++) 10 { 11 str[i-1]+=i; 12 tmp*=i; 13 } 14 tmp=tmp/n; 15 k--; 16 for(int i=n-1;i>0;i--) 17 { 18 int p=k/tmp; 19 k=k%tmp; 20 s+=string(1,str[p]); 21 str.erase(str.begin()+p); 22 tmp=tmp/i; 23 } 24 s+=string(1,str[0]); 25 return s; 26 } 27 };
View Code
转载于:https://www.cnblogs.com/vaecn/p/5348064.html
LC60 Permutation Sequence相关推荐
- 60 Permutation Sequence
60 Permutation Sequence 题目 The set [1,2,3,-,n] contains a total of n! unique permutations.By listing ...
- Permutation Sequence
2019独角兽企业重金招聘Python工程师标准>>> The set [1,2,3,-,n] contains a total of n! unique permutations. ...
- LeetCode60:Permutation Sequence
The set [1,2,3,-,n] contains a total of n! unique permutations. By listing and labeling all of the p ...
- 【数字全排列】LeetCode 60. Permutation Sequence
LeetCode 60. Permutation Sequence Solution0: 偷鸡摸狗的做法 class Solution {public:string getPermutation(in ...
- [Swift]LeetCode60. 第k个排列 | Permutation Sequence
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ ➤微信公众号:山青咏芝(shanqingyongzhi) ➤博客园地址:山青咏芝(https://www.cnblog ...
- 康拓编码——Permutation Sequence
描述 2.1.13 Permutation Sequence The set [1,2,3,ĉ ,n] contains a total of n! unique permutations. By l ...
- 60. Permutation Sequence
一.题目 1.审题 2.分析 给两个数字 n 与 k,返回 1-n 所有数字组成的从小到大的全排序的第 k 个数. 二.解答 1.思路: 方法一.采用字典序列,返回全部序列后,输出第 k 个.(时间超 ...
- LeetCode Permutation Sequence(求排列中的第k个排列是什么)
思路:使用阶乘,f(n) = f(n -1) * n,在确定第i个数是,用k/f(n - 1 - i) 代码如下: public class Solution {public String getP ...
- Leetcode Permutation Sequence
超时算法-排序dfs: class Solution { public: string s; string s1; int count;string getPermutation(int n, int ...
- LeetCode刷题(35)--Permutation Sequence
对于第一个数字,剩余共有(n-1)!中排列,因此第一个数字为k/(n-1)!,之后的数字依次类推 import math class Solution(object):def getPermutati ...
最新文章
- (并查集 建立关系)食物链 -- POJ-- 1182
- 2018总结及2019计划
- 【转】Plotting texts as graphs with R and igraph
- python 定义变量x格式_如何从CSV文件中提取数据列并将它们定义为x和y变量,然后使用pylab在python中绘制它们?...
- Android应用开发之(通过ClipboardManager, ClipData进行复制粘贴)
- 虚拟同步发电机_一种光储型虚拟同步机介绍
- vue 指令 v-model
- 线性时间选择_马鞍山非线性分析工具了解详情_南京凯安软件
- tomcat 日志配置
- STM32 + RT Thread OS 学习笔记[四]
- 帆软图表切换接口和图标轮播接口
- 计算机音乐专业学什么软件有哪些内容,电脑音乐入门装备(软件篇)
- lnmp一键安装-HTTP ERROR 500目前无法处理此请求
- excel报表汇总怎么做?
- wxpython控件旋转_wxPython修改文本框颜色过程解析
- oel6安装oracle报错,OEL6.1下安装Oracle 11gr2 RAC
- 斩获 offer 的 Java 面试宝典
- 功夫熊猫中英文字幕版好句子_了解熊猫中的带有复制警告的设置
- slotformatcombinations_向未授权频谱中的小区应用时隙格式指示的方法和设备与流程...
- [前端] 前端bootstrap col-xs-6 col-md-3的布局意思