VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-ofdifferent-ways-express-n-sum-1-3-4/

⇱ Count of different ways to express N as the sum of 1, 3 and 4 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count of different ways to express N as the sum of 1, 3 and 4

Last Updated : 3 Dec, 2024

Given a positive integer n, the task is to count the number of ways to express as a sum of 1, 3 and 4.

Examples:

Input: n = 4
Output: 4
Explanation: There is 4 ways to represent 4 as sum of 1, 3 and 4: (1+1+1+1), (1+3), (3+1) and (4).

Input: n = 3
Output: 2
Explanation: There is 2 ways to represent 3 as sum of 1, 3 and 4: (1+1+1) and (3).

Using Recursion - O(3^n) Time and O(n) Space

The idea is to recursively explore the possibilities of including 1, 3, or 4 in the sum. For any n, the result can be computed as the sum of ways for n-1, n-3 and n-4.

Mathematically the recurrence relation will look like the following:

countWays(n) = countWays(n-1) + countWays(n-3) + countWays(n-4).

Base Cases:

  • countWays(n) = 0, if n < 0.
  • countWays(n) = 1, if n == 0.

Output
6

Using Top-Down DP (Memoization) - O(n) Time and O(n) Space

If we notice carefully, we can observe that the above recursive solution holds the following two properties of Dynamic Programming:

1. Optimal Substructure: Number of ways to make sum n, i.e., countWays(n), depends on the optimal solutions of the subproblems countWays(n-1), countWays(n-3) and countWays(n-4). By combining these optimal substructures, we can efficiently calculate the number of ways to make sum n.

2. Overlapping Subproblems: While applying a recursive approach in this problem, we notice that certain subproblems are computed multiple times.

  • There is only one parameter: n that changes in the recursive solution. So we create a 1D array of size n for memoization.
  • We initialize this array as -1 to indicate nothing is computed initially.
  • Now we modify our recursive solution to first check if the value is -1, then only make recursive calls. This way, we avoid re-computations of the same subproblems.

Output
6

Using Bottom-Up DP (Tabulation) - O(n) Time and O(n) Space

The idea is to fill the DP table based on previous values. For each n, its value is dependent on n-1, n-3 and n-4. The table is filled in an iterative manner from i = 1 to i = n.

The dynamic programming relation is as follows: 

  • dp[i] = sum(dp[i-j]) for value of j = {1, 3, 4} and i-j >=0.

Output
6

Using Space Optimized DP - O(n) Time and O(1) Space

In previous approach of dynamic programming we have derive the relation between states as given below:

  • dp[i] = sum(dp[i-j]) for value of j = {1, 3, 4} and i - j >=0.

If we observe that for calculating current dp[i] state we only need previous 4 states of dp. There is no need to store all the previous states.


Output
6
Comment
Article Tags: