Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save HaiyangXu/34a07ed52bdc569e14b5 to your computer and use it in GitHub Desktop.
Save HaiyangXu/34a07ed52bdc569e14b5 to your computer and use it in GitHub Desktop.
class Solution {
public:
string getPermutation(int n, int k) {
string re(n,'0');
int fac=factorial(n);
vector<int> vecNum(n,0);
for(int i=1;i<=vecNum.size();++i)vecNum[i-1]=i;
--k;// k=[0,(n-i)! ) ,inorder to get the right index
for(int i=0;i<n;++i)
{
fac=fac/(n-i); //fac=(n-i)!
int index=k/fac;//index of the right number
k=k%fac;
re[i]+=vecNum[index];
vecNum.erase(vecNum.begin()+index);//remove the used number and get a subsequence
}
return re;
}
int factorial(int i)
{
int re=1;
if(!i)return re;
else
while(i)re=re*(i--);
return re;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment