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.
Submission Result: Time Limit Exceede
Last executed input: | 9, 94626 |
我的超时代码:
class Solution { private: vector<vector<int>> res; int my_n; int my_k; bool overFlag; public: void swap(vector<int> &a,int i,int j){ int temp=a[i]; a[i]=a[j]; a[j]=temp; } void dfs(int dep,vector<int> temp,vector<int> v) { if(dep==my_n){ res.push_back(temp); if(res.size()==my_k) overFlag=false; return; } for (int i=dep;i<my_n&&overFlag;++i) { swap(v,dep,i); temp.push_back(v[dep]); dfs(dep+1,temp,v); temp.pop_back(); swap(v,dep,i); } } string getPermutation(int n, int k) { overFlag=true; string resStr(""); vector<int> v; my_n=n; my_k=k; for (int i=1;i<=n;++i) { v.push_back(i); } vector<int> temp; dfs(0,temp,v); vector<int> resV=res[k-1]; for (int i=0;i<resV.size();++i) { resStr.push_back(resV[i]+'0'); } return resStr; } };