backtrack的题就是不敢确定是否可以这样做 这个题的细节就是如何check是否这个格子可以放q 需要一个check function
还有就是先循环行 还是列
其实外层循环是在循环列 在同一行中试图放在不同列中 然后放了一个之后进入下一层recursion 放下一行
同时要注意使用string builder
public class Solution { public List<List<String>> solveNQueens(int n) { List<List<String>> res = new ArrayList<List<String>> (); List<String> list = new ArrayList<String> (); helper ( res, list, 0, n ); return res; } public void helper ( List<List<String>> res, List<String> list, int row, int n ){ if ( row == n ){ res.add( new ArrayList<String>(list)); return; } for ( int i = 0; i < n; i ++ ){ StringBuilder thisRow = new StringBuilder(); for ( int j = 0; j < n; j ++ ){ thisRow.append('.'); } if ( valid ( list, i, n )){ thisRow.setCharAt( i, 'Q'); list.add( thisRow.toString() ); helper ( res, list, row + 1, n); list.remove( list.size() - 1 ); } } } public boolean valid ( List<String> list, int col, int n ){ for ( int i = 0; i < list.size(); i ++ ){ if ( list.get( i ).charAt(col) == 'Q' ) return false; } for ( int i = list.size() - 1; i >= 0; i -- ){ if ( (list.size() - i + col) < n && list.get(i).charAt(list.size() - i + col) == 'Q') return false; } for ( int i = list.size() - 1; i >= 0; i -- ){ if ( (col - list.size() + i) >= 0 && list.get(i).charAt(col - list.size() + i) == 'Q') return false; } return true; } }