题目

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. Luogu P1004/P1006 方格取数/传纸条 【棋盘Dp】 By cellur925

    我明明记得写过这篇啊qwq为什么会搞丢 两题几乎一样. 如果再拓展到k条路,就要用网络流跑了,本蒟现在还不会. 我们容易想到四维dp,但是有一种更好的方法. 首先,先从左上到右下.再从右下到左上可以近 ...

  2. hdu 1695 GCD 欧拉函数 + 容斥

    http://acm.hdu.edu.cn/showproblem.php?pid=1695 要求[L1, R1]和[L2, R2]中GCD是K的个数.那么只需要求[L1, R1 / K]  和 [L ...

  3. 自动判断手机版和pc版

    <html><head><title>欢迎来到手机版</title><script>var ua = navigator.userAgent ...

  4. android环境搭建环境 cordova run android gradle wrapper报错

    cordova run android命令报错 Error: Could not find an installed version of Gradle either in Android Studi ...

  5. Android开源项目:GifView——Android显示GIF动画

    下载:http://code.google.com/p/gifview/downloads/list 简介:android中现在没有直接显示gif的view,只能通过mediaplay来显示,且还常常 ...

  6. Objective-C 里面的类对象复用小结

    OC 提供了单继承 (Inheritance), Category, Extension, Protocol 这几种基本的类与对象层面的复用机制,作一小结. 在这几个机制中,继承提供了纵向的复用,可以 ...

  7. Java EE 目标

    在大三上学期学习了Java se,只是简单的学习了语法,而且没有及时的复习巩固,语法知识已经忘了许多.在这个新学期,又有了Java EE这门课,书上的内容是从没学习过的新知识,只是在网站上看到过像Sp ...

  8. iTOP-4418/6818开发板支持锂电池供电方案

    iTOP-4418/6818开发板支持的是官方推荐的AXP228电池管理,动态调频,更稳定可靠,支持充放电电路与电量计(库化计), 广泛应用于各种电子产品中. 4418开发板中锂电池充放电接口,适用于 ...

  9. python中统计计数的几种方法和Counter的介绍

    使用字典dict()alist=['a','b','a','c','b','b',1,3]count_dict = dict()for i in alist:count_dict[i]=count_d ...

  10. shell脚本的练习

    创建一个以.sh结束的文件. 规则: 文件的头部使用#!/bin/sh 开头   这个是一个标识的作用,告诉使用哪种脚本来执行 echo 用来向命令行来输出的东西