Dynamic Programming
Dynamic programming is a technique used in algorithmic thinking to solve complex problems by breaking them down into smaller overlapping subproblems and efficiently solving each subproblem only once. It is often used to optimize the solution for problems that have overlapping subproblems and exhibit optimal substructure.
One classic example of using dynamic programming is calculating the Fibonacci sequence. The Fibonacci sequence is a sequence of numbers in which each number is the sum of the two preceding ones. Here's an example of calculating the Fibonacci sequence using dynamic programming in C#:
1public int Fibonacci(int n)
2{
3 if (n <= 1)
4 return n;
5
6 int[] fib = new int[n+1];
7 fib[0] = 0;
8 fib[1] = 1;
9
10 for (int i = 2; i <= n; i++)
11 fib[i] = fib[i-1] + fib[i-2];
12
13 return fib[n];
14}
15
16int n = 10;
17int result = Fibonacci(n);
18Console.WriteLine("The Fibonacci sequence at position " + n + " is: " + result);
In this example, we use an array to store the calculated Fibonacci numbers to avoid redundant calculations. By solving the subproblems and storing the results in an array, we can efficiently calculate the Fibonacci sequence at a given position.
Dynamic programming is a powerful technique that can be used to solve a wide range of problems efficiently. It is particularly useful when the problem can be broken down into smaller subproblems that can be solved independently and their solutions can be reused for larger subproblems.
xxxxxxxxxx
public int Fibonacci(int n)
{
if (n <= 1)
return n;
int[] fib = new int[n+1];
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i <= n; i++)
fib[i] = fib[i-1] + fib[i-2];
return fib[n];
}
int n = 10;
int result = Fibonacci(n);
Console.WriteLine("The Fibonacci sequence at position " + n + " is: " + result);