Java AC Backtracking Solution With Memorization


  • 0
    S
    public class Solution {
        public int countArrangement(int N) {
            if (N <= 1) return N;
            int[] visited = new int[N + 1];
            Map<String, Integer> map = new HashMap<>();
            return helper(N, visited, 1, map);
        }
        
        private int helper(int N, int[] visited, int pos, Map<String, Integer> map) {
            if (pos == N + 1) {
                return 1;
            }
            String key = Arrays.toString(visited) + "-" + pos;
            if (map.containsKey(key)) return map.get(key);
            
            int count = 0;
            for (int i = 1; i <= N; ++i) {
                if (visited[i] == 0 && (i % pos == 0 || pos % i == 0)) {
                    visited[i] = 1;
                    count += helper(N, visited, pos + 1, map);
                    visited[i] = 0;
                }
            }
            map.put(key, count);
            return count;
        }
    }
    

Log in to reply
 

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