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, returnnas it is. Fornbeing 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
dparray 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=iis 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.
Lessons in this chapter · Practice with Common Coding Quiz Types
- 1. Coding Quiz - Finding Rotten Apples
- 2. Finding Rotten Apples Explained
- 3. Coding Quiz - Calculating the Sum of a List Recursively
- 4. Explanation for Recursively Calculating the Sum of a List
- 5. Coding Quiz - 1, 2, 3 Addition
- 6. Explanation for Adding 1, 2, 3
- 7. Coding Quiz - Flattening a 2D Array
- 8. Converting to a 1D Array Explanation
- 9. Coding Quiz - Calculate the Sum of a List Using Divide and Conquer
- 10. Explanation of Calculating the Sum of a List Using Divide and Conquer
- 11. Coding Quiz - Gym Uniform Problem
- 12. Gym Uniform Problem Explanation
- 13. Coding Quiz - List of Integers with Sum Greater than Target
- 14. Explanation of Integer List with Sum Greater Than Target
- 15. Coding Quiz - Finding Travel Routes
- 16. Finding Travel Itinerary Explanation
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help