BitWise Operation - Second to None (Only solution when N greater than 15)


  • 0
    S

    public class Solution {
    public int totalNQueens(int n) {
    if (n < 1) return 0;
    int upLimit = (1 << n) - 1;
    int result = solve(upLimit, 0, 0 ,0);
    return result;
    }

    private int solve(int upLimit, int colLimit, int leftLimit, int rightLimit) {
        if (upLimit == colLimit) return 1;
        int pos = upLimit & (~(colLimit | leftLimit | rightLimit)), count = 0;
        while (pos != 0) {
            int mostRightOne = pos & (~pos + 1);
            pos -= mostRightOne;
            count += solve(upLimit, colLimit | mostRightOne,
                          (leftLimit | mostRightOne) << 1,
                          (rightLimit | mostRightOne) >>> 1);    
        }
        return count;
    }
    

    }


Log in to reply
 

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