Skip to content

Commit 2a89bbb

Browse files
refactor 526
1 parent a543e9b commit 2a89bbb

File tree

1 file changed

+28
-56
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+28
-56
lines changed
Lines changed: 28 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -1,61 +1,33 @@
11
package com.fishercoder.solutions;
22

3-
/**
4-
* 526. Beautiful Arrangement
5-
*
6-
* Suppose you have N integers from 1 to N.
7-
* We define a beautiful arrangement as an array that is constructed by these N numbers successfully
8-
* if one of the following is true for the ith position (1 ≤ i ≤ N) in this array:
9-
* The number at the ith position is divisible by i.
10-
* i is divisible by the number at the ith position.
11-
* Now given N, how many beautiful arrangements can you construct?
12-
13-
Example 1:
14-
15-
Input: 2
16-
Output: 2
17-
18-
Explanation:
19-
20-
The first beautiful arrangement is [1, 2]:
21-
Number at the 1st position (i=1) is 1, and 1 is divisible by i (i=1).
22-
Number at the 2nd position (i=2) is 2, and 2 is divisible by i (i=2).
23-
24-
The second beautiful arrangement is [2, 1]:
25-
Number at the 1st position (i=1) is 2, and 2 is divisible by i (i=1).
26-
Number at the 2nd position (i=2) is 1, and i (i=2) is divisible by 1.
27-
28-
Note:
29-
N is a positive integer and will not exceed 15.
30-
*/
313
public class _526 {
32-
public static class Solution1 {
33-
/**
34-
* A good post to look at: https://discuss.leetcode.com/topic/79916/java-solution-backtracking
35-
* and there's a generic template afterwards for backtracking problems
36-
*/
37-
38-
int count = 0;
39-
40-
public int countArrangement(int N) {
41-
backtracking(N, new int[N + 1], 1);
42-
return count;
43-
}
44-
45-
private void backtracking(int N, int[] used, int pos) {
46-
if (pos > N) {
47-
count++;
48-
return;
49-
}
50-
51-
for (int i = 1; i <= N; i++) {
52-
if (used[i] == 0 && (i % pos == 0 || pos % i == 0)) {
53-
used[i] = 1;
54-
backtracking(N, used, pos + 1);
55-
used[i] = 0;
56-
}
57-
}
58-
}
59-
}
4+
public static class Solution1 {
5+
/**
6+
* A good post to look at: https://discuss.leetcode.com/topic/79916/java-solution-backtracking
7+
* and there's a generic template afterwards for backtracking problems
8+
*/
9+
10+
int count = 0;
11+
12+
public int countArrangement(int N) {
13+
backtracking(N, new int[N + 1], 1);
14+
return count;
15+
}
16+
17+
private void backtracking(int N, int[] used, int pos) {
18+
if (pos > N) {
19+
count++;
20+
return;
21+
}
22+
23+
for (int i = 1; i <= N; i++) {
24+
if (used[i] == 0 && (i % pos == 0 || pos % i == 0)) {
25+
used[i] = 1;
26+
backtracking(N, used, pos + 1);
27+
used[i] = 0;
28+
}
29+
}
30+
}
31+
}
6032

6133
}

0 commit comments

Comments
 (0)