Leetcode Permutation Sequence
超时算法—排序dfs:
class Solution {
public:
string s;
string s1;
int count;
string getPermutation(int n, int k)
{
s="123456789";
count=0;
s1="";
dfs(0,n,k);
return s1;
}
void dfs(int depth,int n,int k)
{
if(depth==n&&count<=k)
{
count++;
if(count==k)
{
s1=s.substr(0,n);
return;
}
}
if(depth<n)
{
dfs(depth+1,n,k);
for(int i=depth+1;i<n;i++)
{
string s2=s;
swap(s[depth],s[i]);
sort(s.begin()+depth+1,s.begin()+n);
dfs(depth+1,n,k);
s=s2;
}
}
}
};
超时算法—组合dfs
class Solution {
public:
string s1;
bool used[9];
int count;
char c[9];
string getPermutation(int n, int k)
{
for(int i=0;i<9;i++)
{
used[i]=false;
c[i]='0';
}
count=0;
s1="";
dfs(0,n,k);
return s1;
}
void dfs(int depth,int n,int k)
{
if(depth==n&&count<k)
{
count++;
if(count==k)
{
for(int i=0;i<n;i++)
s1+=c[i];
return;
}
}
if(depth<n)
{
for(int i=0;i<n;i++)
{
if(!used[i])
{
used[i]=true;
c[depth]='0'+i+1;
dfs(depth+1,n,k);
used[i]=false;
}
}
}
}
};
纯数学算法
class Solution {
public:
string getPermutation(int n, int k)
{
string result;
vector<int> num(n);
int i, d(1), q;
for(i=1;i<=n;++i){
num[i-1] = i;
d *= i; //d=n!
}
for(i=n;i>=1;--i){
d = d/i;
q = (k-1)/d;
k = k-q*d;
result.push_back('0'+num[q]);
num.erase(num.begin()+q);
}
return result;
}
};
浙公网安备 33010602011771号