526 Beautiful Arrangement

1. Question

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. 1.
    The number at the ith position is divisible by i.
  2. 2.
    i is divisible by the number at the ith position.
Now given N, how many beautiful arrangements can you construct?
Example 1:
1
Input: 2
2
3
Output: 2
4
5
Explanation:
6
7
The first beautiful arrangement is [1, 2]:
8
9
Number at the 1st position (i=1) is 1, and 1 is divisible by i (i=1).
10
11
Number at the 2nd position (i=2) is 2, and 2 is divisible by i (i=2).
12
13
14
The second beautiful arrangement is [2, 1]:
15
16
Number at the 1st position (i=1) is 2, and 2 is divisible by i (i=1).
17
18
Number at the 2nd position (i=2) is 1, and i (i=2) is divisible by 1.
Copied!
Note:
  1. 1.
    N is a positive integer and will not exceed 15.

2. Implementation

(1) Backtracking
1
class Solution {
2
public int countArrangement(int N) {
3
boolean[] used = new boolean[N + 1];
4
int[] count = new int[1];
5
getArrangement(1, N, used, count);
6
return count[0];
7
}
8
9
public void getArrangement(int curNum, int N, boolean[] used, int[] count) {
10
if (curNum == N + 1) {
11
++count[0];
12
return;
13
}
14
15
for (int i = 1; i <= N; i++) {
16
if (!used[i] && (curNum % i == 0 || i % curNum == 0)) {
17
used[i] = true;
18
getArrangement(curNum + 1, N, used, count);
19
used[i] = false;
20
}
21
}
22
}
23
}
Copied!

3. Time & Space Complexity

Backtracking: 时间复杂度O(N!), 空间复杂度O(N)