Beautiful Arrangement

2018-06-28  本文已影响9人  Frank_Kivi

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;
            }
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读