Given a positive integer N, the task is to find out all the combinations of positive integers that add upto the given integer N. The program should print only combinations, not permutations and all the integers in a combination must be distinct. For example, for input 3, either 1, 2 or 2, 1 should be printed and 1, 1, 1 must not be printed as the integers are not distinct.
Input: N = 3
Input: N = 7
1 2 4
Approach: The approach is an extension of the approach discussed here. The idea used to get all the distinct element is that first we find all the elements that add up to give sum N. Then we iterate over each of the elements and store the elements into the set. Storing the elements into set would remove all the duplicate elements, and after that we add up the sum of the elements of the set and check whether it is equal to N or not.
Below is the implementation of the above approach:
1 2 4 1 6 2 5 3 4 7
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Generate permutation of 1 to N such that absolute difference of consecutive numbers give K distinct integers
- Count of cells in a matrix which give a Fibonacci number when the count of adjacent cells is added
- Print all distinct integers that can be formed by K numbers from a given array of N numbers
- Check if X can give change to every person in the Queue
- Count numbers whose maximum sum of distinct digit-sum is less than or equals M
- All unique combinations whose sum equals to K
- Sum of M maximum distinct digit sum from 1 to N that are factors of K
- Print All Distinct Elements of a given integer array
- Print sorted distinct elements of array
- Print all distinct circular strings of length M in lexicographical order
- Find the sum of numbers from 1 to n excluding those which are powers of K
- Count of distinct numbers in an Array in a range for Online Queries using Merge Sort Tree
- Print all integers that are sum of powers of two given numbers
- Print number in ascending order which contains 1, 2 and 3 in their digits.
- Find sum of non-repeating (distinct) elements in an array
- Check if K distinct array elements form an odd sum
- Minimum number greater than the maximum of array which cannot be formed using the numbers in the array
- Find a pair of elements swapping which makes sum of two arrays same
- Pair with largest sum which is less than K in the array
- Index of the elements which are equal to the sum of all succeeding elements
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.