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.
这道题可以直接穷举然后数第k 个,或者 迭代k次得到返回值,或者直接计算出结果。我用是直接计算结果,很多细节上需要处理。
#include#include using namespace std;class Solution {public: string getPermutation(int n, int k) { if(n <2) return "1"; int tab[10]={ 1}; for(int i =1;i<=9;i++) tab[i] = tab[i-1]*i; int remain[9]={ 0}; for(int i=0;i<9;i++) remain[i]=i+1; int cnt = n; string ret = ""; while(cnt>0){ cnt--; int num = (k-1)/tab[cnt];// cout<<"num="< <