算法作业23

题目地址https://leetcode.com/problems/beautiful-arrangement/#/description
题目描述:Suppose you have N integers from 1 to N. We define a beautiful arrangement as an array that is constructed by these N numbers successfully if one of the following is true for the ith position (1 ≤ i ≤ N) in this array:

The number at the ith position is divisible by i.
i is divisible by the number at the ith position.

Now given N, how many beautiful arrangements can you construct?

我的代码

class Solution {
public:
    int dfs(vector<vector<int>> &a,int* b,int k,int N){
        int num=0;
        for(int i=0;i<a[k].size();i++){
            if(b[a[k][i]]==0){
                b[a[k][i]]=1;
                if(N==k) num++;
                else num+=dfs(a,b,k+1,N);
                b[a[k][i]]=0;
            }
        }
        return num;
    }
    int countArrangement(int N) {
        vector<vector<int>> a(N+1);
        for(int i=1;i<=N;i++)
        for(int j=i;j<=N;j++){
            if(i==j) a[i].push_back(j);
            else if(i%j==0||j%i==0){
                a[i].push_back(j);
                a[j].push_back(i);
            }
        }
        int b[N+1];
        for(int i=0;i<=N;i++) b[i]=0;
        return dfs(a,b,1,N);
    }
};

解题思路
这是一个比较简单回溯算法,获得所有可行的情况,显然我们可以对所有n!种排列都做判断,但复杂度太高,有些情况对于第一个位置就已经不符合,这种做法很不合算。
于是我们先找出每个位置可以放的所有数,放在a中,即a[i]里面存放着所有满足整除i或者被i整除的数。然后对所有这些可能情况进行判断即可,数组b用来保存一个数是否已经放在了之前的位置,保证了数组是1到N的一个排列。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值