Prepin
Log in

Generate all combinations of numbers from 1 to n that add up to n.

Approach / Explanation

This inquiry is about creating code that produces all the possible combinations of numbers from 1 to a specified number n , which sum up to exactly n . This is a typical challenge in combinatorics and dynamic programming. It is crucial to recognize that the combinations may include repeated numbers and that the order of the numbers can differ. For instance, if n equals 4, the combinations are: 1+1+1+1, 1+1+2, 1+3, 2+2, and 4. Here are some important considerations to keep in mind when addressing this problem: Solving this problem recursively is beneficial, as it resembles a decision tree where, at each step, we can select any number from 1 to n . A depth-first search (DFS) approach should be employed to investigate all possible combinations. Always remember to account for the base case, where the sum of the numbers in a combination equals n .

Suggested Answer

Here is an example of Python code that uses a recursive method to address this problem: def print_combinations ( n , combination = [ ] , start = 1 ) : if n < 0 : return elif n == 0 : print ( combination ) else : for i in range ( start , n + 1 ) : print_combinations ( n - i , combination + [ i ] , i ) print_combinations ( 4 ) This code defines the function print_combinations , which takes three arguments: the target number n , the current set of numbers, and the starting point for the next iteration. The function first checks if n is less than 0, returning immediately since a negative sum is not possible. If n is equal to 0, it indicates a valid combination has been found, and it is printed. If n remains greater than 0, the function loops from the starting number to n , making a recursive call to print_combinations with updated parameters.

Alternative Answer

You can also address the issue using Java. Below is a Java code snippet that illustrates this: import java . util . ArrayList ; public class Main { static void printCombinations ( int n , ArrayList < Integer > combination , int start ) { if ( n < 0 ) {

Question Details

Difficulty & Category

Medium

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.