60. Permutation Sequence(unsolved)
来源:互联网 发布:音频算法工程师 编辑:程序博客网 时间:2024/06/05 19:14
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.
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;}};
二刷时
由于上面这种做法我不理解,所以就按照自己做法做了,注意我这种做法会超时的。思路就是先把所有的情况用回溯法都存起来,然后sort排序,再取第k-1个
class Solution {public: vector<string> result; string getPermutation(int n, int k) { string str=""; for(int i=1;i<=n;i++) str=str+to_string(i); solve(str,0,str.size()); sort(result.begin(),result.end()); return result[k-1]; } void solve(string str,int begin,int end){ if(begin==end) { //cout<<str<<endl; result.push_back(str); return ; } for(int i=begin;i<end;i++) { swap(str[begin],str[i]); solve(str,begin+1,end); swap(str[begin],str[i]); } return ; }};
0 0
- 60. Permutation Sequence(unsolved)
- LeetCode --- 60. Permutation Sequence
- [Leetcode] 60. Permutation Sequence
- [leetcode] 60.Permutation Sequence
- 60. Permutation Sequence
- 60. Permutation Sequence
- **LeetCode 60. Permutation Sequence
- leetcode 60. Permutation Sequence
- 60. Permutation Sequence
- 60. Permutation Sequence
- 60. Permutation Sequence
- 60. Permutation Sequence
- 60. Permutation Sequence
- [LeetCode]60. Permutation Sequence
- LeetCode *** 60. Permutation Sequence
- 60. Permutation Sequence
- LeetCode 60. Permutation Sequence
- hiho 60. Permutation Sequence
- MySQL Access denied for user 'root'@'%' to database 'xxx'
- mysql使用总结
- swift 对日期的处理大全( 类扩展 Date+Extension 和 公共类 DateClass)
- java项目跨域问题的简单处理
- linux下代码阅读辅助工具
- 60. Permutation Sequence(unsolved)
- 安卓6.0权限使用
- blog.codedream.ren
- CSDN日报20170228——《技术晋升的评定与博弈》
- srand(time(0)) ;
- Lazy Loading In AngularJS(懒加载)
- CentOS系统Python升级后yum不可用的解决办法
- python day7(20170228 )
- 杭州电子科技大学程序设计竞赛(2016’12)- 网络同步赛