Created
May 11, 2014 01:05
-
-
Save HaiyangXu/34a07ed52bdc569e14b5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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