Beautiful Arrangement

这里因为数据规模已经明显的提示了此题就是回溯,则我们只需要穷举再查重即可,因为这里是定长数,查重可以交给数组来做,另外这道题Python无法用DFS的方法AC,只能用DP,但是这道题的DP目测是涉及了排列组合问题的转移方程,这里暂时不做了

class Solution {
    private int result = 0;
    public int countArrangement(int N) {
        boolean[] array = new boolean[N];
        for (int i = 0; i < N; i++) {
            array[i] = true;
        }
        helper(array, 0, N);
        return result;
    }

    void helper(boolean[] choice, int start, int end) {
        if (start == end) {
            result++;
            return;
        }

        for (int i = 0; i < end; i++) {
            if (choice[i] && ((i + 1) % (start + 1) == 0 || (start + 1) % (i + 1) == 0)) {
                choice[i] = false;
                helper(choice,  start + 1, end);
                choice[i] = true;
            }
        }
    }
}

简直是歧视Python...

results matching ""

    No results matching ""