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.
看到此题,立马想到了暴力,直接搜。但是已提交发现超时了。想了很久,没有办法就找找题解喽。看到题解当时就懂了,做法简单粗暴,但是很有效果。(也是看了别人的题解,然后自己写一下,加深一下印象)。全排列可以分为n个组,每个组的第一位是1~n。每组有(n-1)!个全排列(相当于第二位到最后一位的全排),于是k/(n-1)!就可以得到需要的排列的第一位nums[k/(n-1)!]。然后把该位去掉,后面的数字向前移动,计算第二位时k为k%(n-1)!。以此类推,得到结果。
string int_string(int n){
stringstream ss;
string si;
ss << n;
ss >> si;
return si;
}
string getPermutation(int n, int k) {
int m;
map<int, string> map_ss;
int pcount = 1;
for (m =0; m <n; m++){
map_ss[m] = int_string(m+1);
pcount *= (m + 1);
}
int i;
int num = 0;
k--;
string s="";
for (i = 0; i < n; i++){
pcount /= (n - i);
int selected = k / pcount;
s += map_ss[selected];
k = k%pcount;
int j = selected;
for (; j < n-i-1; j++){
map_ss[j] = map_ss[j + 1];
}
}
return s;
}
用到了一个int转string,以前写过
c++ int 类型与string类型的相互转化