LeetCode: N-Queens II 解题报告
2014-12-18 18:14
399 查看
N-Queens II (LEVEL 4 难度级别,最高级5)
Follow up for N-Queens problem.
View Code
GITHUB:
https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/dfs/totalNQueens_1218_2014.java
Follow up for N-Queens problem.
public class Solution { public int totalNQueens(int n) { if (n == 0) { return 0; } // Bug 1: forget to modify the parameters of the function. return dfs(n, 0, new ArrayList<Integer>()); } public int dfs(int n, int row, ArrayList<Integer> path) { if (row == n) { // The base case: 当最后一行,皇后只有1种放法(就是不放) return 1; } int num = 0; // The queen can select any of the slot. for (int i = 0; i < n; i++) { if (!isValid(path, i)) { continue; } path.add(i); // All the solutions is all the possiablities are add up. num += dfs(n, row + 1, path); path.remove(path.size() - 1); } return num; } public boolean isValid(ArrayList<Integer> path, int col) { int size = path.size(); for (int i = 0; i < size; i++) { // The same column with any of the current queen. if (col == path.get(i)) { return false; } // diagonally lines. // Bug 2: forget to add a ')' if (size - i == Math.abs(col - path.get(i))) { return false; } } return true; } }
View Code
GITHUB:
https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/dfs/totalNQueens_1218_2014.java
相关文章推荐
- [Leetcode] 52. N-Queens II 解题报告
- [leetcode] 52. N-Queens II 解题报告
- 【LeetCode】52.N-Queens II(hard)解题报告
- LeetCode 52. N-Queens II 解题报告
- 【LeetCode】Add Two Numbers 解题报告
- LeetCode-Binary Search Tree Iterator-解题报告
- [leetcode] 278. First Bad Version 解题报告
- Leetcode #38. Count and Say 数数报数 解题报告
- [Leetcode] 364. Nested List Weight Sum II 解题报告
- 【LeetCode】77.Combinations(Medium)解题报告
- 【LeetCode】47.Permutations II(Medium)解题报告
- [LeetCode] Maximum Subarray 解题报告
- 【LeetCode】Reverse Words in a String III 解题报告
- [Leetcode] 604. Design Compressed String Iterator 解题报告
- [leetcode] 54. Spiral Matrix 解题报告
- [LeetCode] Simplify Path 解题报告
- [LeetCode] Two Sum 解题报告
- 【LeetCode】Find Bottom Left Tree Value 解题报告
- 【LeetCode】748. Shortest Completing Word 解题报告(Python)
- [LeetCode] Unique Paths 解题报告