Dynamic programming is a powerful optimization technique that breaks complex problems into simpler subproblems. It stores solutions to avoid redundant calculations, improving efficiency for problems with overlapping subproblems and optimal substructure. Key concepts include memoization, tabulation, and recurrence relations. DP applies to various domains like optimization and graph theory. Common patterns include knapsack problems, longest common subsequence, and shortest path algorithms. Real-world applications span bioinformatics, finance, and robotics.
</>Pythondef fib(n): if n <= 1: return n return fib(n-1) + fib(n-2)
</>Pythondef longestPalindrome(s): n = len(s) dp = [[False] * n for _ in range(n)] ans = "" for length in range(n): for i in range(n - length): j = i + length if length == 0: dp[i][j] = True elif length == 1: dp[i][j] = (s[i] == s[j]) else: dp[i][j] = (s[i] == s[j] and dp[i+1][j-1]) if dp[i][j] and length + 1 > len(ans): ans = s[i:j+1] return ans