classSolution{private:
vector<vector<int>> f;
vector<vector<string>> ret;
vector<string> ans;int n;public:voiddfs(const string& s,int i){if(i == n){
ret.push_back(ans);return;}for(int j = i; j < n;++j){if(f[i][j]){
ans.push_back(s.substr(i, j - i +1));dfs(s, j +1);
ans.pop_back();}}}
vector<vector<string>>partition(string s){
n = s.size();
f.assign(n,vector<int>(n,true));for(int i = n -1; i >=0;--i){for(int j = i +1; j < n;++j){
f[i][j]=(s[i]== s[j])&& f[i +1][j -1];}}dfs(s,0);return ret;}};
62. N皇后
classSolution{public:
vector<vector<string>>solveNQueens(int n){
vector<vector<string>> ans;
vector<int>queens(n);// 皇后放在 (r,queens[r])
vector<int>col(n),diag1(n *2-1),diag2(n *2-1);// vector<int> 效率比 vector<bool> 高auto dfs =[&](auto&& dfs,int r){if(r == n){
vector<string>board(n);for(int i =0; i < n; i++){
board[i]=string(queens[i],'.')+'Q'+string(n -1- queens[i],'.');}
ans.push_back(board);return;}// 在 (r,c) 放皇后for(int c =0; c < n; c++){int rc = r - c + n -1;if(!col[c]&&!diag1[r + c]&&!diag2[rc]){// 判断能否放皇后
queens[r]= c;// 直接覆盖,无需恢复现场
col[c]= diag1[r + c]= diag2[rc]=true;// 皇后占用了 c 列和两条斜线dfs(dfs, r +1);
col[c]= diag1[r + c]= diag2[rc]=false;// 恢复现场}}};dfs(dfs,0);return ans;}};
二分
63. 搜索插入的位置
classSolution{public:intsearchInsert(vector<int>& nums,int target){int n = nums.size();int left =0, right = n -1, ans = n;while(left <= right){int mid =((right - left)>>1)+ left;if(target <= nums[mid]){
ans = mid;
right = mid -1;}else{
left = mid +1;}}return ans;}};