Anagrams:
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
比较Easy的题,用个map记录就是了。其实我可以说我没读懂题,百度人家的才懂吗。
class Solution { public: vector<string> anagrams(vector<string> &strs) { // Start typing your C/C++ solution below // DO NOT write int main() function map<string,vector<string> > mask; vector<string>::iterator it = strs.begin(); for(;it!=strs.end();++it) { string tmp=*it; sort(tmp.begin(),tmp.end()); mask[tmp].push_back(*it); } vector<string> ans; map<string,vector<string> >::iterator mit=mask.begin(); for(;mit!=mask.end();++mit) { if ( (*mit).second.size()>1) { it=(*mit).second.begin(); for(;it!=(*mit).second.end();++it) ans.push_back(*it); } } return ans; } };
N-Queens:
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 the n-queens' placement, where 'Q'
and '.'
both indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ]经典的Q皇后问题,注意左斜线和右斜线的下表即可。
#define vi vector<int> #define vs vector<string> #define vvs vector<vs > class Solution { public: vector<vector<string> > solveNQueens(int n) { // Start typing your C/C++ solution below // DO NOT write int main() function vvs ans; vs grid(n,string(n,'.')); vi col(n,0); vi L2R(2*n,0); vi R2L(2*n,0); solve(ans,grid,col,L2R,R2L,0); return ans; } void solve(vvs& ans,vs& grid, vi& col,vi& L2R,vi& R2L,int x) { int n = grid.size(); if ( x>= n ) { ans.push_back(grid); return; } for(int y=0;y<n;y++) { if ( col[y] || L2R[y-x+n-1] || R2L[x+y] ) continue; col[y]=L2R[y-x+n-1]=R2L[x+y]=1; grid[x][y]='Q'; solve(ans,grid,col,L2R,R2L,x+1); grid[x][y]='.'; col[y]=L2R[y-x+n-1]=R2L[x+y]=0; } } };