LeetCode 52. N-Queens II
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 52. N-Queens II
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
原題鏈接在這里:https://leetcode.com/problems/n-queens-ii/description/
題目:
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
題解:
與N-Queens完全相同,這里只需要返回不同結果的數(shù)量,所以要用一個長度為1的res來計數(shù)。
因為Java是pass by value, 需要這類object結構來保留中間結果。
Time Complexity: expontenial. Space: O(n). 生成的row大小為n. 用了O(n)層stack.
AC Java:
1 public class Solution { 2 public int totalNQueens(int n) { 3 int [] res = new int[1]; 4 dfs(n,0,new int[n], res); 5 return res[0]; 6 } 7 //遞歸寫dfs, 每次往row里面加一個數(shù),若是合法就繼續(xù)dfs 8 private void dfs(int n, int cur, int [] row, int [] res){ 9 if(cur == n){ 10 res[0]++; 11 return; 12 } 13 for(int i = 0; i<n; i++){ 14 row[cur] = i; 15 if(isValid(cur, row)){ 16 dfs(n, cur+1, row, res); 17 } 18 } 19 } 20 //檢查現(xiàn)在row 還是否合法 21 private boolean isValid(int cur, int [] row){ 22 for(int i = 0; i<cur; i++){ 23 if(row[cur] == row[i] || Math.abs(row[cur]-row[i]) == cur-i){ 24 return false; 25 } 26 } 27 return true; 28 } 29 }?
轉載于:https://www.cnblogs.com/Dylan-Java-NYC/p/4920126.html
總結
以上是生活随笔為你收集整理的LeetCode 52. N-Queens II的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 没有学过功夫能否练神功
- 下一篇: 一些常见http状态码