码迷,mamicode.com
首页 > 其他好文 > 详细

数字三角形

时间:2019-04-21 12:56:33      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:测试   数字   str   nbsp   names   pac   out   using   oid   

测试样例:

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 }

 

数字三角形

标签:测试   数字   str   nbsp   names   pac   out   using   oid   

原文地址:https://www.cnblogs.com/zouma/p/10744272.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!