LeetCode 526 Beautiful Arrangement

本文探讨了如何根据特定条件构造出所有可能的美丽排列。通过递归算法实现,该算法接受一个整数N作为输入,并返回所有可能的排列数量,其中每个位置上的数字要么能被其位置整除,要么其位置能被该数字整除。

摘要生成于 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
      /**
	 * @param N
	 * @return
	 */
	public static int countArrangement(int N) {
		return arrangement(1, new boolean[N + 1], 0);
		//数组长N+1为了方便从1开始计算
 
	}
 
	/**
	 * @param cur
	 *            已经算了几个数
	 * @param visited
	 * @param count
	 */
	public static int arrangement(int cur, boolean[] visited, int count) {
		if (cur > visited.length - 1) {
			count++;//已经计算的超过了N个说明都计算过了,那么count+1
			return count;
		}
		for (int i = 1; i < = visited.length - 1; i++) {
			if (!visited[i] && (i % cur == 0 || cur % i == 0)) {
				visited[i] = true;
				count = arrangement(cur+1, visited, count);
				visited[i] = false;
			}
		}
		return count;
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值