【Leetcode】526. 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?

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.

Note:
  1. N is a positive integer and will not exceed 15.

Difficulty: Medium


思路:

首先,初步尝试在随着N递增时寻找Beautiful 排列规律,发现并无明显的规律可寻,而且所有排列需要穷举才可找到。
如果直接穷举递归,需要进行全排列,则算法的时间复杂度为O(n!),效率太低不可取。
对于解决穷举问题,可以考虑使用回溯算法。回溯是递归的一种形式,可以用来解决是否有解、求所有解和求最优解的问题。简单来说,假设有一棵树,需要找到所有从树的根节点到叶节点的遍历方式,回溯算法会从根开始,然后选择一个根的节点,再从根的节点的节点进行选择,重复地进行直到找到一个叶节点,找到叶节点后会返回上一次遍历的节点寻找其他未遍历的其他节点,这样省去了重复的遍历过程,保证每次遍历都是新的。

根据回溯的思路,同样,可以对本题的Beautiful排列实现。比如,当N为5时,使用回溯算法先是得到(1,2,3,4,5)排列,符合要求,符合要求的排列数count+1,接着回溯到第四个位置,在剩下的选择中选5,但发现5不符合要求,然后跳过,不再往后判断。同样当得到(1,2,5)这前三个排列时,5已经不符合要求,也不会再往后判断(1,2,5,x,x)。这样减少了直接穷举递归方法中很多不需要判断操作,提高了效率。
以下是用Java的实现过程。

public class Solution {
    int count = 0;

    public int countArrangement(int N) {
        if (N == 0) return 0;
        helper(N, 1, new int[N + 1]);
        return count;
    }

    private void helper(int N, int pos, int[] used) {
        if (pos > N) {
            count++;
            return;
        }

        for (int i = 1; i <= N; i++) {
            if (used[i] == 0 && (i % pos == 0 || pos % i == 0)) {
                used[i] = 1;
                helper(N, pos + 1, used);
                used[i] = 0;
            }
        }
    }
}

具体来说,计算Beautiful排列的数量,可把长度为N的排列的位置看成结点,建立一个辅助类来记录所遍历结点的位置及在该位置符合要求的值,当结点的位置超过N长度则认为完成了一次Beautiful排列。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值