![]() |
VOOZH | about |
Given a positive integer n, the task is to count the number of ways to express n 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).
Table of Content
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.
6
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.
6
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.
6
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.
6