数字三角形
Posted zouma
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数字三角形相关的知识,希望对你有一定的参考价值。
测试样例:
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
这种方法的时间复杂度为O(2n),需要继续优化
1 #include<iostream> 2 #include<algorithm> 3 using namespace std; 4 constexpr int MAX = 101; 5 int D[MAX][MAX]; 6 int n; 7 int Maxsum(int i, int j) 8 { 9 if (i == n) 10 return D[i][j]; 11 else 12 return max(Maxsum(i + 1, j), Maxsum(i + 1, j + 1)) + D[i][j]; 13 } 14 int main(void) 15 { 16 int i, j; 17 cin >> n; 18 for (i = 1; i<=n;++i) 19 { 20 for (j = 1; j <= i; ++j) 21 { 22 cin >> D[i][j]; 23 } 24 } 25 cout << Maxsum(1, 1) << endl; 26 return 0; 27 }
这种方法的时间复杂度为O(n2),需要继续优化
1 #include<iostream> 2 #include<algorithm> 3 using namespace std; 4 constexpr int MAX = 101; 5 int D[MAX][MAX]; 6 int maxsum[MAX][MAX]; 7 int n; 8 int Maxsum(int i, int j) 9 { 10 if (maxsum[i][j] != -1) 11 return maxsum[i][j]; 12 if (i == n) 13 maxsum[i][j] = D[i][j]; 14 else 15 { 16 maxsum[i][j] = max(Maxsum(i+1,j), Maxsum(i+1,j+1))+ D[i][j]; 17 } 18 return maxsum[i][j]; 19 } 20 int main(void) 21 { 22 int i, j; 23 cin >> n; 24 for (i = 1; i<=n;++i) 25 { 26 for (j = 1; j <= i; ++j) 27 { 28 cin >> D[i][j]; 29 maxsum[i][j] = -1; 30 } 31 } 32 cout << Maxsum(1, 1) << endl; 33 return 0; 34 }
这种方法与上一种相同,时间复杂度为O(n2),需要继续优化
1 #include<iostream> 2 #include<algorithm> 3 using namespace std; 4 constexpr int MAX = 101; 5 int D[MAX][MAX]; 6 int maxsum[MAX][MAX]; 7 int n; 8 int main(void) 9 { 10 int i, j; 11 cin >> n; 12 for (i = 1; i<=n;++i) 13 { 14 for (j = 1; j <= i; ++j) 15 { 16 cin >> D[i][j]; 17 } 18 } 19 for (j = 1; j <= n; ++j) 20 { 21 maxsum[n][j] = D[n][j]; 22 } 23 for (i = n - 1; i >= 1; --i) 24 { 25 for (j = 1; j <= i; ++j) 26 { 27 maxsum[i][j] = max(maxsum[i + 1][j], maxsum[i + 1][j + 1]) + D[i][j]; 28 } 29 } 30 31 cout <<maxsum[1][1]<< endl; 32 return 0; 33 }
这种方法与上一种相同,时间复杂度为O(n2),但空间复杂度为O(n)
1 #include<iostream> 2 #include<algorithm> 3 using namespace std; 4 constexpr int MAX = 101; 5 int D[MAX][MAX]; 6 int *maxsum; 7 int n; 8 int main(void) 9 { 10 int i, j; 11 cin >> n; 12 for (i = 1; i<=n;++i) 13 { 14 for (j = 1; j <= i; ++j) 15 { 16 cin >> D[i][j]; 17 } 18 } 19 maxsum = D[n]; 20 for (i = n - 1; i >= 1; --i) 21 { 22 for (j = 1; j <= i; ++j) 23 { 24 maxsum[j] = max(maxsum[j], maxsum[j + 1]) + D[i][j]; 25 } 26 } 27 cout <<maxsum[1]<< endl; 28 return 0; 29 }
以上是关于数字三角形的主要内容,如果未能解决你的问题,请参考以下文章