Leetcode526. 回溯法之应用(一):统计数组排列数目

Leetcode526. Beautiful Arrangement

题目

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?

Example:
Input: 2
Output: 2
Explanation:
The first beautiful arrangement is [1, 2]:
Number at the 1st position (i=1) is 1, and 1 is divisible by i (i=1).
Number at the 2nd position (i=2) is 2, and 2 is divisible by i (i=2).
The second beautiful arrangement is [2, 1]:
Number at the 1st position (i=1) is 2, and 2 is divisible by i (i=1).
Number at the 2nd position (i=2) is 1, and i (i=2) is divisible by 1.

解题分析

拿到这道题,可能第一想法就是找找规律,但很遗憾其实规律挺难找的。我们可以这样考虑,从最后一个数n出发,尝试将这个数与前面一个数进行交换,如果交换后的数组满足要求,就进一步进行交换。如果交换后不满足要求,就后退一步,将两个数交换回来。
其实我上面描述的思想就是回溯法的思想。 回溯算法实际上是一个类似枚举的搜索尝试过程。其基本思想是,在包含问题的所有解的解空间树中,按照深度优先搜索的策略,从根结点出发深度探索解空间树。当探索到某一结点时,要先判断该结点是否包含问题的解,如果包含,就从该结点出发继续探索下去,如果该结点不包含问题的解,则逐层向其祖先结点回溯。
上面我就将最大的数字作为根节点,将其它数字作为其叶子节点。每往前访问一个数,就尝试将其与前面的数字交换,这其实就是探索的过程。如果交换后满足条件就继续往前交换,这就很类似深度优先探索了;如果不满足条件就交换回来,往祖先节点回溯。所以当根节点的所有子树都被访问也即遍历到最小的一个数时,这个过程就结束了,结果也就出来了。下面是这个算法的源代码。

源代码

class Solution {
public:
    int number = 0;

    int countArrangement(int N) {
        int* nums = new int[N + 1];
        for (int i = 0; i <= N; i++) {
            nums[i] = i;
        }
        count(nums, N);
        return number;
    }

    void count(int* nums, int n) {
        if (n == 0) {
            number++;
            return;
        }
        for (int i = n; i > 0; i--) {
            swap(nums[i], nums[n]);
            if (nums[n] % n == 0 || n % nums[n] == 0) {
                count(nums, n - 1);
            }
            swap(nums[n], nums[i]);
        }
    }
};

以上是我对这道问题的一些想法,有问题还请在评论区讨论留言~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值