思路:首先写一个检查能不能摆的函数.boolean checkValid(int[] columns,int row1, int column1);意思是row1行摆在column1列可不可以. 然后是place函数.第一个参数row表示现在摆第几行.第一行可以摆n次位置,然后往下也是8ci.也就是相当于8^8次检查.如果能摆了,往下一行,如果不能摆往后移一列.当row>8说明摆好了.那么计数器+1. 答案: public class Solution{ public static void m…
Write an algorithm to print all ways of arranging eight queens on an 8*8 chess board so that none of them share the same row, column or diagonal. 思路: 本质上是DFS, 从第一行开始一行行地放棋子,每次放棋子之前根据当前的棋盘检查一下约束. Code (from book): void placeQueen(int row, Integer[] co…
面试题9.1:有个小孩正在上楼梯,楼梯有n个台阶,小孩一次可以上1阶.2阶或者3阶.实现一个方法,计算小孩有多少种上楼梯的方式. 思路:第4个数是前三个数之和 注意:能不能使用递归,能不能建立一个很大的数组来存储传递的参数(因为可能有空间的限制),要%1000000007防止超出范围 package cc150.recursion_dp; public class GoUpstairs { public static void main(String[] args) { // TODO 自动生成…
Follow up for N-Queens problem. Now, instead outputting board configurations, return the total number of distinct solutions. 这道题是之前那道N-Queens N皇后问题 的延伸,说是延伸其实我觉得两者顺序应该颠倒一样,上一道题比这道题还要稍稍复杂一些,两者本质上没有啥区别,都是要用回溯法Backtracking来解,如果理解了之前那道题的思路,此题只要做很小的改动即可,不…
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. Each solution contains a distinct board configuration of…