leetcode [60] 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 for n = 3:
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the k^th permutation sequence.
Note:
Given n will be between 1 and 9 inclusive.
Given k will be between 1 and n! inclusive.
Example 1:
Input: n = 3, k = 3
Output: "213"
Example 2:
Input: n = 4, k = 9
Output: "2314"
题目大意:
给一个数n,将1到n之间的数进行全排列,后按字符顺序进行排序,得到排序过后的第k个组合。
解法:
我一开始想的是将1到n的数采用回溯法进行全排列,得到排列组合的所有可能,将所有可能再进行排序,取第k个,但是这种做法会导致TLE。
这种做法的C++代码如下:
class Solution {
public:
void dfs(int n,string tmp,vector<bool>&visited,vector<string>& res){
if(tmp.size()==n) res.push_back(tmp);
for(int i=1;i<=n;i++){
if(visited[i]) continue;
visited[i]=true;
dfs(n,tmp+to_string(i),visited,res);
visited[i]=false;
}
}
string getPermutation(int n, int k) {
vector<string>res;
vector<bool>visited(n,false);
string s="";
dfs(n,s,visited,res);
sort(res.begin(),res.end());
return res[k-1];
}
};
想到上一次做的https://www.cnblogs.com/xiaobaituyun/p/10581093.html这道题,可以不停的得到下一个排列组合,一直得到第k个。
这种做法采用了c++的内置函数next_permutation。
class Solution {
public:
string getPermutation(int n, int k) {
string res="";
for(int i=1;i<=n;i++) res=res+to_string(i);
for(int i=1;i<k;i++) next_permutation(res.begin(),res.end());
return res;
}
};
不用C++的内置函数:
class Solution {
public:
void nextPermutation(string &str){
int i=str.size()-1;
for(;i>0;i--){
if(str[i-1]<str[i]) break;
}
if(i==0) sort(str.begin(),str.end());
for(int j=str.size()-1;j>=i;j--){
if(str[j]>str[i-1]){
swap(str[i-1],str[j]);
break;
}
}
sort(str.begin()+i,str.end());
}
string getPermutation(int n, int k) {
string res="";
for(int i=1;i<=n;i++) res=res+to_string(i);
for(int i=1;i<k;i++){
nextPermutation(res);
}
return res;
}
};

浙公网安备 33010602011771号