动态规划算法的入门教程:动态规划算法:(1)入门介绍及案例分析
接下来通过 最长回文子串 来加深对动态规划算法的理解。
1、问题描述:
2、思路分析:
3、代码:
if __name__ == "__main__":
s = input()
dp = [[0 for _ in range(len(s))] for _ in range(len(s))]
ans = 1
for i in range(len(s)-1):
dp[i][i] = 1
if s[i] == s[i+1]:
dp[i][i+1] = 1
for L in range(3, len(s)+1):
for i in range(len(s)):
j = i + L - 1
if j < len(s):
if s[i] == s[j] and dp[i+1][j-1] == 1:
dp[i][j] = 1
ans = L
else:
break
print(ans)
结果:
#include <iostream>
using namespace std;
const int maxn = 100;
int main()
{
string s;
cin >> s;
int len = s.size();
int dp[maxn][maxn] = { 0 };
int ans = 1;
for (int i = 0; i < len; i++)
{
dp[i][i] = 1;
if (i < len - 1)
{
if (s[i] == s[i + 1])
{
dp[i][i + 1] = 1;
ans = 2;
}
}
}
for (int L = 3; L <= len; L++)
{
for (int i = 0; i + L - 1 < len; i++)
{
int j = i + L - 1;
if (s[i] == s[j] && dp[i + 1][j - 1] == 1)
{
dp[i][j] = 1;
ans = L;
}
}
}
cout << ans << endl;
return 0;
}
结果:
4、总结:
动态规划算法的核心在于如何设计状态转移方程,而这也是动态规划算法最难的地方。
动态规划算法:(1)入门介绍及案例分析
|