62. 不同路径
- 相关标签: 数组 动态规划
/*
dfs ->超时 37 / 62 得DP
dp[n][m] = dp[n][m-1] + dp[n-1][m]
*/
#define BUFLEN 101
// void dfs(int graph[BUFLEN][BUFLEN], int m, int n, int *res, int i, int j)
// {
// if (i == n -1 && j == m -1) {
// (*res)++;
// return;
// }
// if (i + 1 <= n - 1) {
// dfs(graph, m, n, res, i + 1, j);
// }
// if (j + 1 <= m - 1) {
// dfs(graph, m, n, res, i, j + 1);
// }
// }
int uniquePaths(int m, int n){
int res = 0;
// int graph[BUFLEN][BUFLEN] = {0};
int dp[BUFLEN][BUFLEN] = {0};
// dfs(graph, m, n, &res, 0, 0);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (i == 0 && j == 0) {
dp[i+1][j + 1] = 1;
continue;
}
dp[i + 1][j + 1] = dp[i + 1][j] + dp[i][j + 1];
}
}
// return res;
return dp[n][m];
}
1007. 行相等的最少多米诺旋转
- 相关标签 :贪心算法 数组
看了下题目解析, 本意是用贪心做的, 这边直接用哈希下了
后续在 看下 贪心怎么解
/*
2 1 2 4 2 2
5 2 6 2 3 2
3 5 1 2 3
3 6 3 3 4
4 4 3 4
3 3 4 3
4 , OK
3, OK 不影响
*/
int helper(int *l1, int *l2, int maxi, int size)
{
// l1 为参照, l2 往L1 翻转, L1 是 含有MAXi数字大的那个
int res = 0;
for (int i = 0; i < size; i++) {
if (l1[i] != maxi) {
if (l2[i] == maxi) {
res++;
} else {
return -1;
}
}
}
return res;
}
#define HMSIZE 7
int minDominoRotations(int* A, int ASize, int* B, int BSize){
if (ASize == 1) {
return 0;
}
int hma[HMSIZE] = {0};
int hmb[HMSIZE] = {0};
for (int i = 0; i < ASize; i++) {
hma[A[i]] += 1;
hmb[B[i]] += 1;
}
int max = 0;
int maxi;
for (int i = 0; i < HMSIZE; i++) { // 找出最大的那个
if (hma[i] + hmb[i] > max) {
max = hma[i] + hmb[i];
maxi = i;
}
}
if (max < ASize) { // 小于 一般的话 肯定不行
return -1;
}
// printf("%d, %d- %d\n", hma[maxi], hmb[maxi], maxi);
int res = 0;
if (hma[maxi] > hmb[maxi]) {
res = helper(A, B, maxi, ASize);
} else {
res = helper(B, A, maxi, ASize);
}
return res;
}
1161. 最大层内元素和
- 相关标签: 图
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
#define BUFLEN 300
void recur(struct TreeNode* root, int *val, int level, int *levelLen)
{
if (root == NULL) {
(*levelLen) = (level > (*levelLen)) ? level : (*levelLen);
return;
}
val[level] += root->val;
recur(root->left, val, level + 1, levelLen);
recur(root->right, val, level + 1, levelLen);
}
int maxLevelSum(struct TreeNode* root){
int val[BUFLEN] = {0};
int levelLen = 0;
recur(root, val, 1, &levelLen);
int max = INT_MIN;
for (int i = 1; i < levelLen; i++) {
max = (val[i] > max) ? val[i] : max;
}
for (int i = 1; i < levelLen; i++) {
if (val[i] == max) {
return i;
}
}
return 0;
}