60.全排列
来源:互联网 发布:淘宝上警服叫什么 编辑:程序博客网 时间:2024/05/16 06:29
Permutation Sequence
问题描述:
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.
知识补充:
#divmod函数//本函数是实现a除以b,然后返回商与余数的元组。如果两个参数a,b都是整数,那么会采用整数除法,结果相当于(a//b, a % b)。如果a或b是浮点数,相当于(math.floor(a/b), a%b)。index, k = divmod(k, n)
参考答案(C++):
class Solution {public: string getPermutation(int n, int k) { int i,j,f=1; // left part of s is partially formed permutation, right part is the leftover chars. string s(n,'0'); for(i=1;i<=n;i++){ f*=i; s[i-1]+=i; // make s become 1234...n } for(i=0,k--;i<n;i++){ f/=n-i; j=i+k/f; // calculate index of char to put at s[i] char c=s[j]; // remove c by shifting to cover up (adjust the right part). for(;j>i;j--) s[j]=s[j-1]; k%=f; s[i]=c; } return s; }};
性能:
参考答案(python):
import mathclass Solution: # @param {integer} n # @param {integer} k # @return {string} def getPermutation(self, n, k): numbers = range(1, n+1) permutation = '' k -= 1 while n > 0: n -= 1 # get the index of current digit index, k = divmod(k, math.factorial(n)) permutation += str(numbers[index]) # remove handled number numbers.remove(numbers[index]) return permutation
性能:
阅读全文
0 0
- 60.全排列
- 全排列
- 全排列
- 全排列
- 全排列
- 全排列
- 全排列
- 全排列
- 全排列
- 全排列
- 全排列
- 全排列
- 全排列
- 全排列
- 全排列
- 全排列
- 全排列
- 全排列
- 阿里云服务器搭建FTP
- 列表字典元组集合 容易出现的各种函数 方法已经小问题 (想到哪里写哪里)
- zipper[POJ]动态规划实现
- 逆元 (数论倒数)
- arm内存映射
- 60.全排列
- 几个项目管理软件的比较
- Scrapy Item Loaders机制详解
- 单例模式
- eclipse中应知道的一些快捷操作方式
- retrofit+RecyclerView+SwipeRefreshLayout下拉刷新上拉加载+item点击
- JavaScript 箭头函数(Lambda表达式)
- iOS 代码关闭App
- 浅析javascript中的this关键字