首页 > 代码库 > Permutation Sequence
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.
Note: Given n will be between 1 and 9 inclusive.
思路:使用标准库函数next_permutation循环k-1次求解将会超时。对于最高位n,其取值每加1,对应增加(n-1)!个排列实例。于是,对于给定的k,最高位的取值应为:(k-1) / (n-1)!。因此,可以考虑从高往低逐位确定每一位的取值。
1 class Solution { 2 public: 3 string getPermutation( int n, int k ) { 4 int factorial = n; 5 string permutation, selection( n, ‘1‘ ); 6 for( int i = 1; i < n; ++i ) { 7 factorial *= i; 8 selection[i] += i; 9 }10 for( int i = 0; i < n && k > 0; ++i ) {11 factorial /= (n-i);12 int select = (k-1) / factorial;13 k %= factorial;14 permutation.push_back( selection[select] );15 selection.erase( select, 1 );16 }17 permutation.insert( permutation.end(), selection.rbegin(), selection.rend() );18 return permutation;19 }20 };
Permutation Sequence
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。