Java easy dfs


  • 0
    public class Solution {
        private int count = 0;
        public int countArrangement(int n) {
            boolean[] chosen = new boolean[n + 1];
            countArrangementHelper(chosen, n, 1);
            return count;
        }
        
        private void countArrangementHelper(boolean[] chosen, int n, int pos) {
            if (pos == n + 1) {
                count++;
                return;
            }
    
            for (int i = 1; i <= n; i++) {
                if (!chosen[i] && (i % pos == 0 || pos % i == 0)) {
                    chosen[i] = true;
                    countArrangementHelper(chosen, n, pos + 1);
                    chosen[i] = false;
                }
            }
        }
    }

Log in to reply
 

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