Dynamic Programming
Dynamic Programming
Dynamic Programming
>> Dynamic programming is a problem-solving technique
that involves
>> breaking down complex problems into simpler
overlapping subproblems
>> and solving each subproblem only once,
>> storing the results to avoid redundant computation.
1. Recursion:
>>In this method, the problem is solved by breaking it
down into smaller subproblems, which are solved
recursively.
>> It is the simplest and most intuitive approach but
can lead to redundant computations.
Problem
Calculate the nth Fibonacci number, where F(0) = 0 and
F(1) = 1, and for n > 1, F(n) = F(n-1) + F(n-2).
----------Recursion method----------
int fibonacci(int n) {
if (n <= 1)
return n;
return
fibonacci(n - 1) + fibonacci(n - 2);
}
int fibonacci(int n) {
int dp[n + 1];
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= n; ++i) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
return memo[m][n];
}
--------------Recursion--------------
return memo[n][amount];
}
4. Knapsack Problem
Given a set of items, each with a weight and a value,
determine the maximum value you can obtain by
selecting a subset of the items, such that the sum of
the weights of the selected items does not exceed a
given weight limit.
---------------Recursion-------------------
memo[n][W] = max(
values[n - 1] + knapsack(weights, values, n -
1, W - weights[n - 1]),
knapsack(weights, values, n - 1, W)
);
return memo[n][W];
}