N-Queens II -- LeetCode

原题链接: http://oj.leetcode.com/problems/n-queens-ii/ 

这道题跟N-Queens算法是完全一样的,只是把输出从原来的结果集变为返回结果数量而已。思路我们就不在赘述了,大家可以参见N-Queens,算法的时间复杂度仍然是指数量级的,空间复杂度是O(n)。代码如下:

public int totalNQueens(int n) {
    ArrayList res = new ArrayList();
    res.add(0);
    helper(n,0,new int[n],res);
    return res.get(0);
}
private void helper(int n, int row, int[] columnForRow, ArrayList res)
{
    if(row==n)
    {
        res.set(0,res.get(0)+1);
        return;
    }
    for(int i=0;i
这道题目我个人没有看到从输出结果集变为输出结果数量有什么可提升的空间,不像 Unique Paths ,输出结果集还是数量是有不同复杂度的解法的。如果这个题大家有什么更优的解法,可以留言或者发邮件到 [email protected] 给我交流一下哈。

你可能感兴趣的:(LeetCode,LeetCode总结)