Explanation for Adding 1, 2, 3
The challenge is to find all possible combinations of a given number n
as a sum of 1
, 2
, and 3
.
This function employs the dynamic programming
technique using the tabulation method
.
Tabulation involves storing computed results in a table, allowing reuse of these values in further calculations.
Function Implementation
-
Handle Base Cases
:-
When
n < 3
, returnn
as it is. Forn
being 1 or 2, the possible combinations are 1 and 2 respectively. -
If
n == 3
, the number of combinations is 4, hence return 4.
-
-
Initialize Array for Tabulation
:- The
dp
array is initialized as[0, 1, 2, 4]
. Here,dp[i]
will store the number of combinations forn=i
.
- The
-
Calculate Number of Combinations Using Dynamic Programming
:- For each number from 4 to
n
, updatedp[i]
by summingdp[i - 1]
,dp[i - 2]
, anddp[i - 3]
. This implies that the number of ways to reachn=i
is the sum of ways to reachn=i-1
,n=i-2
, andn=i-3
.
- For each number from 4 to
def solution(n): # Handle base cases if n < 3: return n if n == 3: return 4 # Initialize array for tabulation dp = [0, 1, 2, 4] # Calculate number of combinations using dynamic programming for i in range(4, n + 1): dp.append(dp[i - 1] + dp[i - 2] + dp[i - 3]) return dp[n]
Usage Example
print(solution(4)) # Output: 7
When calling solution(4)
, the number of combinations to form 4 are:
- 1 + 1 + 1 + 1
- 1 + 1 + 2
- 1 + 2 + 1
- 2 + 1 + 1
- 2 + 2
- 1 + 3
- 3 + 1
Thus, there are 7 such ways, correctly confirmed by the function returning 7.
Lecture
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help