526. Beautiful Arrangement

本文介绍了一种使用递归算法来解决特定数学问题的方法——寻找所有可能的美丽排列的数量。美丽排列是指由1到N的整数组成的数组,其中每个元素i的位置上的数字要么能被i整除,要么i能被该位置上的数字整除。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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:

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

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

Example 1:

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.
这道题用递归求解。

1、递归的条件是:num%i==0 || i %num==0

2、helper需要的参数:可以存integer的list,记录当前数有没有被用过的boolean类型数组used,计数用的count,目标值n

代码如下:

public class Solution {
    int count;
    
    public int countArrangement(int N) {
        count = 0;
        helper(new ArrayList<Integer>(), new boolean[N + 1], N);
        return count;
    }
    
    private void helper(List<Integer> list, boolean[] used, int n) {
        if (list.size() == n) {
            count ++;
        }
        for (int i = 1; i <= n; i ++) {
            if (!used[i]) {
                int id = list.size() + 1;
                if (id % i == 0 || i % id == 0) {
                    list.add(i);
                    used[i] = true;
                    helper(list, used, n);
                    list.remove(list.size() - 1);
                    used[i] = false;
                }
            }
        }
    }
}
上面的代码相当于从第一位,一直放到最高位,这道题只是计数,没让保存,可以把list替换成一个index,代码稍微改变一下。代码如下:

public class Solution {
    public int countArrangement(int N) {
        boolean[] arr = new boolean[N+1];
        return find(arr, N);
    }
    
    private int find(boolean[] arr, int idx){
        if(idx==0){ return 1; }
        
        int res = 0;
        for(int i=1; i<arr.length; i++){
            if(!arr[i] && (idx%i==0 || i%idx==0)){
                arr[i] = true;
                res += find(arr, idx-1);
                arr[i] = false;
            }
        }
        return res;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值