zoukankan      html  css  js  c++  java
  • 数塔问题(递归/递推)

    递归写法 从上往下
    在这里插入图片描述

    #include<iostream>
    #include<vector>
    #include<queue>
    #include<stack>
    #include<string>
    #include<math.h>
    #include<algorithm>
    #include<map>
    #include<cstring>
    #include<set>
    using namespace std;
    const int maxn = 1100;
    int f[maxn][maxn], dp[maxn][maxn];
    int n;
    
    int getans(int i, int j)
    {
    	if (dp[i][j] != 0)
    		return dp[i][j];
    	if (i == n)
    		return f[i][j];
    	
    	dp[i][j] = max(getans(i+1,j), getans(i+1,j+1)) + f[i][j];
    
    	return dp[i][j];
    }
    int main()
    {
    	
    	cin >> n;
    	for (int i = 1; i <= n; i++)
    	{
    		for (int j = 1; j <= i; j++)
    		{
    			cin >> f[i][j];
    		}
    	}
    	cout << getans(1, 1);
    }
    
    

    递推写法 从下往上

    #include<iostream>
    #include<vector>
    #include<queue>
    #include<stack>
    #include<string>
    #include<math.h>
    #include<algorithm>
    #include<map>
    #include<cstring>
    #include<set>
    using namespace std;
    const int maxn = 1100;
    int f[maxn][maxn], dp[maxn][maxn];
    int n;
    
    int main()
    {
    	cin >> n;
    	for (int i = 1; i <= n; i++)
    	{
    		for (int j = 1; j <= i; j++)
    		{
    			cin >> f[i][j];
    		}
    	}
    	for (int j = 1; j <= n; j++)
    	{
    		dp[n][j] = f[n][j];
    	}
    	for (int i = n - 1; i >= 1; i--)
    	{
    		for (int j = 1; j <= i; j++)
    		{
    			dp[i][j] = max(dp[i + 1][j], dp[i + 1][j + 1]) + f[i][j];
    		}
    	}
    	cout << dp[i][j] << endl;
    	return 0;
    }
    
  • 相关阅读:
    mysql关联查询
    MySQL数据库面试题(转发来自https://thinkwon.blog.csdn.net/article/details/104778621)
    iview + vue + thinphp5.1 源码
    <!--标签嵌套规则-->
    PHP的基本变量检测方法
    PHP的八种变量
    php变量命名规范
    C++11新特性-常用
    算法设计-DP常见问题及解题技巧
    Web开发-概述
  • 原文地址:https://www.cnblogs.com/Hsiung123/p/13811991.html
Copyright © 2011-2022 走看看