力扣超时题:优美的排列

122 篇文章 0 订阅
95 篇文章 0 订阅
文章比较了两种解决LeetCode排列问题的C++代码,原始代码由于递归结构导致超时,而优化后的版本通过调整dfs函数参数,减少了无效递归,提高了效率。
摘要由CSDN通过智能技术生成

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;
    }
};

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值