最原始的DP,空间和时间复杂度O(n^2)。在线
#include "stdio.h"
#include "string.h"
#define M 100
#define MIN(a, b) ((a)<(b)?(a):(b))
int num[M] = {2, 1, 67, 33, 53, 21, 6, 35, 44, 61};
int n = 10;
int dp[M][M];
void DP(){
int i, j;
memset(dp, 0, sizeof(dp));
for(i=0; i<n; i++)
dp[i][i] = num[i];
for(j=1; j<n; j++){
for(i=0; i+j<n; i++)
dp[i][i+j] = MIN(dp[i][i+j-1], dp[i+1][i+j]);
}
}
void main(){
int i, j;
DP();
for(j=1; j<n; j++){
for(i=0; i+j<n; i++)
printf("%d-%d:%d ", i, i+j, dp[i][i+j]);
printf("\n");
}
}
转换一下,j表示从i开始,长度为j的这段区间,时间空间复杂度和上面相同。在线
#include "stdio.h"
#include "string.h"
#define M 100
#define MIN(a, b) ((a)<(b)?(a):(b))
int num[M] = {2, 1, 67, 33, 53, 21, 6, 35, 44, 61};
int n = 10;
int dp[M][M];
void DP(){
int i, j;
memset(dp, 0, sizeof(dp));
for(i=0; i<n; i++)
dp[0][i] = num[i];
for(j=1; j<n; j++){
for(i=0; i+j<n; i++)
dp[j][i] = MIN(dp[j-1][i], dp[j-1][i+1]);
}
}
void main(){
int i, j;
DP();
for(j=1; j<n; j++){
for(i=0; i+j<n; i++)
printf("%d-%d:%d ", i, i+j, dp[j][i]);
printf("\n");
}
}
滚动数组,空间复杂度降到O(n),时间复杂度没减少。离线
#include "stdio.h"
#include "string.h"
#define M 100
#define MIN(a, b) ((a)<(b)?(a):(b))
int num[M] = {2, 1, 67, 33, 53, 21, 6, 35, 44, 61};
int n = 10;
int dp[2][M];
void DP(){
int i, j;
int p, q;
memset(dp, 0, sizeof(dp));
p = 0; q = 1;
for(i=0; i<n; i++)
dp[p][i] = num[i];
for(j=1; j<n; j++){
for(i=0; i+j<n; i++){
dp[q][i] = MIN(dp[p][i], dp[p][i+1]);
printf("%d-%d:%d ", i, i+j, dp[q][i]);
}
p = (p+1)%2; q = (q+1)%2;
printf("\n");
}
}
void main(){
DP();
}
还是用稀疏表(ST)好一些吧