https://www.lintcode.com/problem/beautiful-arrangement/description
public class Solution {
private int result = 0;
/**
* @param N: The number of integers
* @return: The number of beautiful arrangements you can construct
*/
public int countArrangement(int N) {
// Write your code here
boolean[] visited = new boolean[N];
treeWalk(visited, 0);
return result;
}
private void treeWalk(boolean[] visited, int i) {
if (i == visited.length) {
result++;
return;
}
for (int j = 0; j < visited.length; j++) {
if (visited[j]) {
continue;
}
if ((j + 1) % (i + 1) == 0 || (i + 1) % (j + 1) == 0) {
visited[j] = true;
treeWalk(visited, i + 1);
visited[j] = false;
}
}
}
}
网友评论