N-Queens II

来源:互联网 发布:ps如何做淘宝首页 编辑:程序博客网 时间:2024/06/06 09:01

Follow up for N-Queens problem.

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

Show Tags

Have you met this question in a real interview?

思路:跟N-queen I 一样,不需要build result,只需要count就行了。

public class Solution {    public int totalNQueens(int n) {        if(n<=0) return 0;        int[] rowpos = new int[n];        int[] count = {0};        collect(rowpos, 0, n, count);        return count[0];    }        public void collect(int[] rowpos, int row, int n, int[] count) {        if(row == n){            count[0]++;            return;        }                for(int i=0; i<n; i++){            rowpos[row] = i;            if(checkvalid(rowpos, row)){                collect(rowpos, row+1, n, count);            }        }    }        public boolean checkvalid(int[] rowpos, int row){        for(int i=0; i<row; i++){            if(rowpos[i] == rowpos[row] || row-i == Math.abs(rowpos[row] - rowpos[i])){                return false;            }        }        return true;    }}


0 0
原创粉丝点击