|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 | 3 | /**
|
4 |
| - * 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 |
| 4 | + * 526. Beautiful Arrangement |
| 5 | + * Suppose you have N integers from 1 to N. |
| 6 | + * We define a beautiful arrangement as an array that is constructed by these N numbers successfully |
5 | 7 | * if one of the following is true for the ith position (1 ≤ i ≤ N) in this array:
|
6 | 8 |
|
7 | 9 | The number at the ith position is divisible by i.
|
|
30 | 32 | N is a positive integer and will not exceed 15.
|
31 | 33 | */
|
32 | 34 | public class _526 {
|
33 |
| - //A good post to look at: https://discuss.leetcode.com/topic/79916/java-solution-backtracking and it's generic template afterwards for backtracking problems |
34 |
| - |
35 |
| - int count = 0; |
36 |
| - |
37 |
| - public int countArrangement(int N) { |
38 |
| - backtracking(N, new int[N + 1], 1); |
39 |
| - return count; |
40 |
| - } |
41 |
| - |
42 |
| - private void backtracking(int N, int[] used, int pos) { |
43 |
| - if (pos > N) { |
44 |
| - count++; |
45 |
| - return; |
46 |
| - } |
47 |
| - for (int i = 1; i <= N; i++) { |
48 |
| - if (used[i] == 0 && (i % pos == 0 || pos % i == 0)) { |
49 |
| - used[i] = 1; |
50 |
| - backtracking(N, used, pos + 1); |
51 |
| - used[i] = 0; |
52 |
| - } |
53 |
| - } |
54 |
| - } |
| 35 | + /**A good post to look at: https://discuss.leetcode.com/topic/79916/java-solution-backtracking |
| 36 | + * and there's a generic template afterwards for backtracking problems*/ |
| 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 | + for (int i = 1; i <= N; i++) { |
| 51 | + if (used[i] == 0 && (i % pos == 0 || pos % i == 0)) { |
| 52 | + used[i] = 1; |
| 53 | + backtracking(N, used, pos + 1); |
| 54 | + used[i] = 0; |
| 55 | + } |
| 56 | + } |
| 57 | + } |
55 | 58 |
|
56 | 59 | }
|
0 commit comments