Very elegant and easy java solution by dfs


  • 0
    D
    public int countArrangement(int N) {
        return dfs(N, 1, new boolean[N+1]);
    }
    
    private int dfs(int N, int index, boolean[] used) {
        if(index == N + 1) {
            return 1;
        }
        
        int res = 0;
        
        for(int i = 1; i <= N; i++) {
            if(!used[i] && (i % index == 0 || index % i == 0)) {
                used[i] = true;
                res += dfs(N, index + 1, used);
                used[i] = false;
            }
        }
        
        return res;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.