22. 括号生成 - 力扣(LeetCode)
dfs生成合法的括号序列即可
class Solution {
public:vector<string> ans;void dfs(int l, int r, int n, string& s){if (s.size() == n * 2){ans.push_back(s);return;}if (l){s += "(";dfs(l - 1, r, n, s);s.pop_back();}if (r && r > l){s += ")";dfs(l, r - 1, n, s);s.pop_back();}}vector<string> generateParenthesis(int n) {string s; s += "(";dfs(n - 1, n, n, s);return ans;}
};
54. 螺旋矩阵 - 力扣(LeetCode)
遍历方向为右下左上,根据该方向定义dx,dy方向数组
遍历时保存记录,遇到访问过的或者越界,则需要替换方向
class Solution {
public:vector<int> spiralOrder(vector<vector<int>>& matrix) {int dx[4] = { 0, 1, 0, -1 };int dy[4] = { 1, 0, -1, 0 };int m = matrix.size(), n = matrix[0].size();vector<vector<int>> st(m, vector<int>(n, 0));int i = 0, j = 0; int d = 0;vector<int> ans;while (ans.size() != m * n){ans.push_back(matrix[i][j]);st[i][j] = 1;int x = i + dx[d], y = j + dy[d];if (x < 0 || x >= m || y < 0 || y >= n || st[x][y]) {d ++ ;d %= 4;}i += dx[d], j += dy[d];}return ans;}
};