Implement dynamic programming solution for tribonacci and fix index calculation in sequence matching

This commit is contained in:
2025-12-06 00:03:28 +08:00
parent cf633352b5
commit 7ae0aeb744
2 changed files with 13 additions and 2 deletions

View File

@@ -4,4 +4,14 @@
#include <solution/1137.h> #include <solution/1137.h>
int tribonacci(int n) int tribonacci(int n)
{ {
int dp[n + 1];
dp[0] = 0;
if (n >= 1)
dp[1] = 1;
if (n >= 2)
dp[2] = 1;
for (int i = 3; i <= n; i++)
dp[i] = dp[i - 3] + dp[i - 2] + dp[i - 1];
return dp[n];
} }

View File

@@ -14,19 +14,20 @@ int maxRepeating(char *sequence, char *word)
return 0; return 0;
int dp[n]; int dp[n];
memset(dp, 0, sizeof(dp));
for (int i = m - 1; i < n; i++) for (int i = m - 1; i < n; i++)
{ {
bool valid = true; bool valid = true;
for (int j = 0; j < m; j++) for (int j = 0; j < m; j++)
{ {
if (sequence[i - m + 1] != word[j]) if (sequence[i - m + 1 + j] != word[j])
{ {
valid = false; valid = false;
break; break;
} }
} }
if (valid) if (valid)
dp[i] = (i == m - 1 ? 0 : dp[i - m] + 1); dp[i] = (i == m - 1 ? 0 : dp[i - m]) + 1;
} }
int ret = dp[0]; int ret = dp[0];