intmaxSubArray(vector<int>& nums){ int res = nums[0]; int dp = nums[0]; for (int i = 1; i < nums.size(); i++) { dp = max(dp + nums[i], nums[i]); res = dp > res ? dp : res; } return res; }
动态规划让我觉得自己是渣渣。
题目描述
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
vector<int> spiralOrder(vector<vector<int>>& matrix) { int m = matrix.size(); if (!m)return {}; int n = matrix[0].size(); if (!n)return {}; vector<int> res = {};
int i = 0, j = 0; int base_i = 0, base_j = 0;
while (true) { while (j < n) { res.push_back(matrix[i][j]); j++; } j = n - 1; base_i++; if (base_i == m)break; i = base_i; while (i < m) { res.push_back(matrix[i][j]); i++; } i = m - 1; n--; if (n == base_j)break; j = n - 1; while (j >= base_j) { res.push_back(matrix[i][j]); j--; } j = base_j; m--; if (base_i == m)break; i = m - 1; while (i >= base_i) { res.push_back(matrix[i][j]); i--; } i = base_i; base_j++; if (base_j == n)break; j = base_j; } return res; }
doublemyPow(double x, int n){ if (x == 1)return1; double res = 1; for (int i = n; i != 0; i /= 2) { if (i % 2)res *= x; x *= x; } return n < 0 ? 1 / res : res; }
题目描述
n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上。
给定一个整数 n,返回所有不同的 n 皇后问题的解决方案。每一种解法包含一个明确的 n 皇后问题的棋子放置方案,该方案中 ‘Q’ 和 ‘.’ 分别代表了皇后和空位。
string s = ""; for (int i = 0; i < n; i++) s = s + '.'; for (int i = 0; i < n; i++) model.push_back(s); heng = newbool[n]; shu = newbool[n]; int t = 2 * n - 1; pie = newbool[t]; na = newbool[t]; for (int i = 0; i < n; i++) { heng[i] = true; shu[i] = true; } for (int i = 0; i < t; i++) { pie[i] = true; na[i] = true; } dfs(res, 0, n, 0); return res; }
intjump(vector<int>& nums){ //贪心算法 if (nums.size() == 1)return0; int reach = 0, nextreach = nums[0], steps = 0; for (int i = 0; i < nums.size(); i++) { int t = nums[i] + i; if (t > nextreach)nextreach = t;//尽量走得远 if (nextreach >= nums.size() - 1) return steps+1; if (i == reach) { reach = nextreach;//可跳 steps++; } } return steps; }
图的广度优先遍历可以找到某节点到所有节点最少步数,图的深度优先遍历可以找到无环图的拓扑结构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
intjump(vector<int>& nums){ //bfs int steps = 0; int start = 0, end = 0; int max; while (end < nums.size() - 1) { max = end; for (int i = start; i <= end; i++) { int t = i + nums[i]; if (max < t) max = t; } start = end + 1;//往前走一步 end = max; steps++; } return steps; }
stringmultiply(string num1, string num2){ if (num1 == "0" || num2 == "0")return"0"; int len1 = num1.length(); int len2 = num2.length(); int i = len1 + len2 - 2; string res = ""; int c = 0, x = 0; while (i >= 0) { x = c;//c表示上一次的进位 for (int j = i < len1 ? i : (len1 - 1); i - j < len2 && j >= 0; j--) x += ((num1[j] - '0')*(num2[i - j] - '0')); c = x / 10; x = x % 10; res = char('0' + x) + res; i--; } if(c)res = char('0' + c) + res; return res; }