526. 优美的排列 - 力扣(LeetCode)
我的超时代码
class Solution {
public:
int count=0;
vector<int>path;
bool check[16]={false};
void dfs(int n)
{
if(n+1==path.size())
{
bool t=true;
for(int i=1;i<=n;i++)
{
if(path[i]%(i)!=0&&(i)%path[i]!=0)
{
t=false;
break;
}
}
if(t==true)
{
count++;
}
return ;
}
for(int i=1;i<=n;i++)
{
if(check[i]==false)
{
check[i]=true;
path.push_back(i);
dfs(n);
path.pop_back();
check[i]=false;
}
}
}
int countArrangement(int n) {
path.push_back(0);
dfs(n);
return count;
}
};
正确代码
class Solution {
public:
int count=0;
vector<int>path;
bool check[16]={false};
void dfs(int pos,int n)
{
if(pos==n+1)
{
count++;
return ;
}
for(int i=1;i<=n;i++)
{
if(check[i]==false&&(pos%i==0||i%pos==0))
{
check[i]=true;
dfs(pos+1,n);
check[i]=false;
}
}
}
int countArrangement(int n) {
dfs(1,n);
return count;
}
};