您的位置:首页 > 产品设计 > UI/UE

[leetcode-52]N-QueensII(java)

2015-08-03 09:32 561 查看
问题描述:

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

分析:该题与上道基本一样,只是有些细节需要改变一下,比如这题要求返还的是count值,而这个值是不能通过传参进去来得到的。所以只能通过返回值来实现。

代码如下:248ms

[code]    private int  solve(int n,int index,List<Integer> tmpList){
        if(n==index){
            return 1;
        }
        int count = 0;
        for(int col = 0;col<n;col++){
            int row = index;
            int rowList;
            for(rowList = 0;rowList<tmpList.size();rowList++){
                int rowrow = rowList;
                int colcol = tmpList.get(rowrow);
                //同一列
                if(col == colcol)
                    break;
                //同一斜线
                if(Math.abs(rowrow-row)==Math.abs(colcol-col))
                    break;
            }
            if(rowList==tmpList.size()) {
                tmpList.add(col);
                int val = solve(n, index + 1, tmpList);
                tmpList.remove(tmpList.size()-1);
                if(val>0) {
                    count += val;
                }
            }
        }
        return count;
    }
    public int totalNQueens(int n){
        List<Integer> tmpList = new LinkedList<>();
        return solve(n, 0, tmpList);
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: