Java backtracking solution


  • 0
    int total;
    public int countArrangement(int N) {
        Set<Integer> visitedIndex = new HashSet<>();
        total = 0;
        helper(N,visitedIndex,N);
        return total;
    }
    private void helper(int curr, Set<Integer> visitedIndex,int N){
        for(int j = 1;j<=N;j++){
            if((curr%j==0||j%curr==0)&&!visitedIndex.contains(j)){
                if(curr>1){
                    visitedIndex.add(j);
                    helper(curr-1,visitedIndex,N);
                    visitedIndex.remove(j);
                }
                else{
                    total+=1;
                }
            }
        }
    }

Log in to reply
 

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