Sponsored
Sponsored
In this approach, we solve the problem by checking all possible combinations or configurations naively. Although not efficient for large inputs, this approach is often straightforward and can provide insights into the problem structure.
Time Complexity: O(n).
Space Complexity: O(1), as no extra space is used other than loop variables.
1public class Solution {
2 public static void solve(int n) {
3 // Brute force approach in Java
4 for (int i = 0; i < n; i++) {
5 System.out.print(i + " ");
6 }
7 System.out.println();
8 }
9
10 public static void main(String[] args) {
11 solve(10);
12 }
13}
This Java program uses a simple for-loop to print numbers from 0 to n-1, demonstrating a rudimentary brute force approach.
This approach utilizes dynamic programming to optimize the solution by storing interim results and eliminating redundant calculations seen in a brute force approach. This method can significantly improve efficiency when dealing with complex recursive problems.
Time Complexity: O(n).
Space Complexity: O(n) due to the storage array.
1using System;
class Solution {
static int[] dp = new int[1000];
static int Solve(int n) {
if (n <= 1) return n;
if (dp[n] != -1) return dp[n];
return dp[n] = Solve(n-1) + Solve(n-2);
}
static void Main() {
Array.Fill(dp, -1);
Console.WriteLine(Solve(10));
}
}
In C#, dynamic programming is used for calculating Fibonacci numbers, with an array for memoization to optimize computation.