Simple and short C++ backtracking solution


  • 0
    A
    class Solution {
    public:
        int helper(int used, int i, int n) {
            if (i == 1)
                return 1;
            
            int ans = 0;
            for (int j = 1; j <= n; ++j) {
                int bit = 1 << j;
                if ( !(used & bit) && (!(i % j) || !(j % i)) )
                    ans += helper(used | bit, i - 1, n);
            }
            return ans;
        }
    
        int countArrangement(int N) {
            return helper(0, N, N);
        }
    };
    

Log in to reply
 

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