【DFS】LeetCode 526. 优美的排列

题目链接

526. 优美的排列

思路

【DFS】LeetCode 46. 全排列思路类似。

代码

class Solution {
    private int result = 0;
    private boolean[] used;

    public int countArrangement(int n) {
        used = new boolean[n + 1];
        dfs(1, n);

        return result;
    }

    void dfs(int currentPos, int n){
        if(currentPos > n){
            result++;
            return;
        }

        for(int i = 1; i <= n; i++){
            if((i % currentPos == 0 || currentPos % i == 0) && !used[i]){
                used[i] = true;
                dfs(currentPos + 1, n);
                used[i] = false;
            }
        }
    }
}
posted @ 2023-03-07 10:22  Frodo1124  阅读(17)  评论(0编辑  收藏  举报