Easy Java DFS Solution


  • 0
    D
     public class Solution {
        public int countArrangement(int N) {
            boolean[] isVisited = new boolean[N+1];
            int count = 0;
            for(int i = 1; i <= N; i++) {
                isVisited[i] = true;
                count += dfs(N, i, 1, isVisited);
            
                isVisited[i] = false;
            }
        
            return count;
        }
    
        private int dfs(int n, int number, int index, boolean[] isVisited) {
            if(((number % index != 0) && (index % number != 0))) {
                return 0;
            }
        
           if(index == n) {
                return 1;
           }
        
           int count = 0;
        
           for(int i = 1; i <= n; i++) {
              if(isVisited[i]) {
                  continue;
              }
            
              isVisited[i] = true;
              count += dfs(n, i, index + 1, isVisited);
              isVisited[i] = false;
          }
        
          return count;
    }
    

    }


Log in to reply
 

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