首页 > 其他 > 详细

Leetcode 526 优美的排列

时间:2020-08-07 00:18:49      阅读:108      评论:0      收藏:0      [点我收藏+]

技术分享图片

  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;
    }
}

技术分享图片

 

Leetcode 526 优美的排列

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!