Java easy to understand back-tracking solution


  • 0
    K
    public class Solution {
        int count;
        public Solution()
        {
            count = 0;
        }
        public int countArrangement(int N) {
            valid(N, new ArrayList<Integer>());
            return count;
        }
        
        public void valid(int N, List<Integer> l)
        {
            if(l.size() > 0 && l.get(l.size()-1) % (l.size()) != 0 && (l.size()) % l.get(l.size()-1) != 0)
            {
                return;
            }
            
            if(l.size() == N)
            {
                ++count;
                return;
            }
            for(int i = 1; i <= N; ++i)
            {
                if(l.contains(i)) continue;
                l.add(i);
                valid(N, l);
                l.remove(l.size()-1);
            }
        }
    }
    

Log in to reply
 

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