题目

The set [1,2,3,…,n] contains a total of n! unique permutations.

By listing and labeling all of the permutations in order,

We get the following sequence (ie, for n = 3):

“123”

“132”

“213”

“231”

“312”

“321”

Given n and k, return the kth permutation sequence.

Note: Given n will be between 1 and 9 inclusive.

分析

首先想到的是,采用STL库中的标准算法next_permutation(),寻找第k个排列即可,可是提交结果为Time Limited Exceed,显然,必须寻找更优算法。

借鉴了别人的思想,设计如下(原文博客):

数学解法

在n!个排列中,第一位的元素总是(n-1)!一组出现的,也就说如果p = k / (n-1)!,那么排列的最开始一个元素一定是nums[p]。

假设有n个元素,第K个permutation是

a1, a2, a3, ….. …, an

那么a1是哪一个数字呢?

那么这里,我们把a1去掉,那么剩下的permutation为

a2, a3, …. …. an, 共计n-1个元素。 n-1个元素共有(n-1)!组排列,那么这里就可以知道

设变量K1 = K

a1 = K1 / (n-1)!

同理,a2的值可以推导为

a2 = K2 / (n-2)!

K2 = K1 % (n-1)!

…….

a(n-1) = K(n-1) / 1!

K(n-1) = K(n-2) /2!

an = K(n-1)

STL标准算法实现(Time Limited Exceed)

class Solution {
public:
string getPermutation(int n, int k) {
if (n <= 0 || k <= 0 || k > factorial(n))
return ""; vector<int> v;
for (int i = 1; i <= n; i++)
v.push_back(i); int index = 1;
while (index < k && next_permutation(v.begin(), v.end()))
index++; string str = "";
for (int i = 0; i < n; i++)
str += IntToStr(v[i]);
str += '\0'; return str; } string IntToStr(int n)
{
string str = ""; while (n != 0)
{
str += (n % 10 + '0');
n /= 10;
} reverse(str.begin(), str.end()); return str;
} long factorial(int n)
{
if (n <= 1)
return 1;
else
return n * factorial(n - 1);
}
};

AC代码

class Solution {
public: string getPermutation(int n, int k) {
vector<int> nums(n); int pCount = 1;
for (int i = 0; i < n; ++i) {
nums[i] = i + 1;
pCount *= (i + 1);
} k--;
string res = "";
for (int i = 0; i < n; i++) {
pCount = pCount / (n - i);
int selected = k / pCount;
res += ('0' + nums[selected]); for (int j = selected; j < n - i - 1; j++)
nums[j] = nums[j + 1];
k = k % pCount;
}
return res;
} };

GitHub测试程序源码

LeetCode(60) Permutation Sequence的更多相关文章

  1. LeetCode(60): 第k个排列

    Medium! 题目描述: 给出集合 [1,2,3,…,n],其所有元素共有 n! 种排列. 按大小顺序列出所有排列情况,并一一标记,当 n = 3 时, 所有排列如下: "123" ...

  2. Leetcode(1)两数之和

    Leetcode(1)两数之和 [题目表述]: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标.你可以假设每种输入只会对应一 ...

  3. Leetcode(3)无重复字符的最长子串

    Leetcode(3)无重复字符的最长子串 [题目表述]: 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度. 第一种方法:暴力 执行用时:996 ms: 内存消耗:12.9MB 效果: ...

  4. Leetcode(8)字符串转换整数

    Leetcode(8)字符串转换整数 [题目表述]: 请你来实现一个 atoi 函数,使其能将字符串转换成整数. 首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止. 当我 ...

  5. Qt 学习之路 2(60):使用 DOM 处理 XML

    Qt 学习之路 2(60):使用 DOM 处理 XML  豆子  2013年8月3日  Qt 学习之路 2  9条评论 DOM 是由 W3C 提出的一种处理 XML 文档的标准接口.Qt 实现了 DO ...

  6. LeetCode(275)H-Index II

    题目 Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimi ...

  7. LeetCode(220) Contains Duplicate III

    题目 Given an array of integers, find out whether there are two distinct indices i and j in the array ...

  8. LeetCode(154) Find Minimum in Rotated Sorted Array II

    题目 Follow up for "Find Minimum in Rotated Sorted Array": What if duplicates are allowed? W ...

  9. LeetCode(122) Best Time to Buy and Sell Stock II

    题目 Say you have an array for which the ith element is the price of a given stock on day i. Design an ...

随机推荐

  1. Tech 助力Fin ,大数据风控系统赋能掌众金服!

    胡亚海 首席技术官  CTO 北京航空航天大学  博士 深耕互联网领域近20年,先后任职于普天信息技术研究院.摩托罗拉.宇龙酷派.百度等知名企业,曾主导宇龙酷派公司全员从WinCE向Android转型 ...

  2. Java Genericity

    四.  Java Genericity 1.  Genericity 泛型 泛型 <T> 1. 泛型就是参数化类型 2. 作用:安全,方便 3. 适用于对多种数据类型执行相同功能的代码,主 ...

  3. K - KazaQ’s Socks

    Bryce1010模板 #include <bits/stdc++.h> using namespace std; #define LL long long int main() { LL ...

  4. ACM数论-求组合数

    我们利用这个公式求阶乘和逆元求阶: #include<cstdio> const int N = 200000 + 5; const int MOD = (int)1e9 + 7; int ...

  5. QT5每日一学(五)QT布局管理器

    Qt中的布局管理器主要包括 QBoxLayout基本布局管理器 QGridLayout栅格布局管理器 QFormLayout窗体布局管理器 而基本布局管理器又分为QHBoxLayout水平布局管理器和 ...

  6. synchronized(4)修饰语句块之:synchronized(this)

    synchronized(this) 此时,线程获得的是对象锁.例如: public class Thread8 extends Thread { public void sync_fun() { s ...

  7. c#拖拽文件

    在“属性”窗口中,先设置MDI的父窗口的AllowDrop 属性更改为true;2.在父窗口的事件中添加下面两个事件 private void Form1_DragEnter(object sende ...

  8. 阿里云设置指定ip访问实例

    添加安全组规则 添加允许访问的外网IP,优先级设置为1,并将所有ip设置为拒绝访问,优先级设置为2. 参考地址: https://help.aliyun.com/document_detail/254 ...

  9. iOS---数据离线缓存

    离线缓存 为了用户的体验,不需要每次打开App都加载新数据,或者重新请求数据,因此需要把每次浏览的数据保存起来,当下次打开软件时,首先从沙盒中加载数据:或者当软件未联网时,也只能从沙盒中加载旧数据. ...

  10. PowerShell让系统可以执行.ps1文件,开机,关机,在线时间 , Function自定义函数

    Function Get-ComputerUptimeHistory { $q=' <QueryList> <Query Id="0" Path="Sy ...