@@ -0,0 +1,1563 @@
+/***%0A * Follow up for N-Queens problem.%0A *%0A * Now, instead outputting board configurations, return the total number of distinct solutions.%0A */%0A%0Aimport java.util.ArrayList;%0A%0Apublic class Solution %7B%0A    public int totalNQueens(int n) %7B%0A        if (n == 0) return 0;%0A        StringBuffer sb = new StringBuffer();%0A        for (int i = 0; i %3C n; i++)%0A            sb.append('.');%0A        StringBuffer%5B%5D solve = new StringBuffer%5Bn%5D;%0A        for (int i = 0; i %3C n; i++)%0A            solve%5Bi%5D = new StringBuffer(sb.toString());%0A        boolean%5B%5D cols = new boolean%5Bn%5D;%0A        int%5B%5D row = new int%5Bn%5D;%0A        int %5B%5D ret = new int%5B1%5D;%0A        findSolutions(n, 0, ret, solve, row, cols);%0A        return ret%5B0%5D;%0A    %7D%0A%0A    private void findSolutions(int n, int start, int%5B%5D ret,%0A            StringBuffer%5B%5D solve, int%5B%5D row, boolean%5B%5D cols) %7B%0A        if (start == n) %7B%0A            ret%5B0%5D++;%0A            return;%0A        %7D%0A%0A        for (int i = 0; i %3C n; i++) %7B%0A            if (cols%5Bi%5D) continue;%0A            boolean ok = true;%0A            for (int j = 0; j %3C start; j++) %7B%0A                if (Math.abs(start - j) == Math.abs(i - row%5Bj%5D)) %7B%0A                    ok = false;%0A                    break;%0A                %7D%0A            %7D%0A            if (ok) %7B%0A                cols%5Bi%5D = true;%0A                solve%5Bstart%5D.setCharAt(i, 'Q');%0A                row%5Bstart%5D = i;%0A                findSolutions(n, start + 1, ret, solve, row, cols);%0A                row%5Bstart%5D = 0;%0A                solve%5Bstart%5D.setCharAt(i, '.');%0A                cols%5Bi%5D = false;%0A            %7D%0A        %7D%0A    %7D%0A%7D%0A

add NQueensII.java