N-Queens II 解答

Question

Follow up for N-Queens problem.

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

Solution

This problem seems like 2D DP, but it is not.

For DP problem, usually we will have a/ some directions. But here, we can go to all four directions. So this can not be solved by DP.

We still use the way to implement N-Queens.

There is one stuff worth mentioning:

In java, if in function f(x), we pass a variable x of primitive data type like int into a function g(x), the value of x in f(x) is not changed.

If we want it to be modified, we need to pass a reference.

 1 public class Solution {
 2     
 3     public int totalNQueens(int n) {
 4         // Should use an object rather than a int variable here
 5         // We want "result" to be modified in helper function
 6         int[] result = {0};
 7         int[] queen = new int[n];
 8         helper(n, 0, queen, result);
 9         return result[0];
10     }
11     
12     private void helper(int n, int rowNum, int[] queen, int[] result) {
13         if (n == rowNum) {
14             result[0]++;
15             return;
16         }
17         
18         for (int i = 0; i < n; i++) {
19             queen[rowNum] = i;
20             if (check(rowNum, queen))
21                 helper(n, rowNum + 1, queen, result);
22         }
23     }
24     
25     private boolean check(int rowNum, int[] queen) {
26         int colNum = queen[rowNum];
27         for (int i = 0; i < rowNum; i++) {
28             if ((colNum == queen[i]) || (queen[i] - i == colNum - rowNum) || (queen[i] + i == colNum + rowNum))
29                 return false;
30         }
31         return true;
32     }
33 }

 

转载于:https://www.cnblogs.com/ireneyanglan/p/4888816.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值