Leetcode 526 优美的排列

  JAVA:

 int an = 0;

    public final int countArrangement(int N) {
        search(N, new HashSet<Integer>(), 0);
        return an;
    }

    private final void search(int n, Set<Integer> history, int rePoint) {
        if (rePoint == n) {
            an++;
            return;
        }
        int nextPoint = rePoint + 1;
        for (int i = 1; i <= n; i++) {
            if (history.contains(i) || (i % nextPoint != 0 && nextPoint % i != 0)) {
                continue;
            }
            history.add(i);
            search(n, history, nextPoint);
            history.remove(i);
        }
    }

  JS:

var an = 0;
var countArrangement = function (N) {
    an = 0;
    search(N, new Array(N + 1).fill(false), 0);
    return an;
};

var search = function (n, path, point) {
    if (point === n) {
        an++;
        return;
    }
    let nextPoint = point + 1;
    for (let i = 1; i <= n; i++) {
        if (path[i]) {
            continue;
        }
        if (nextPoint % i != 0 && i % nextPoint != 0) {
            continue;
        }
        path[i] = true;
        search(n, path, nextPoint);
        path[i] = false;
    }
}

原文地址:https://www.cnblogs.com/niuyourou/p/13445879.html