Given a number n (number of variables) and val (sum of the variables), find out how many such nonnegative integral solutions are possible.
Input : n = 5, val = 1 Output : 5 Explanation: x1 + x2 + x3 + x4 + x5 = 1 Number of possible solution are : (0 0 0 0 1), (0 0 0 1 0), (0 0 1 0 0), (0 1 0 0 0), (1 0 0 0 0) Total number of possible solutions are 5 Input : n = 5, val = 4 Output : 70 Explanation: x1 + x2 + x3 + x4 + x5 = 4 Number of possible solution are: (1 1 1 1 0), (1 0 1 1 1), (0 1 1 1 1), (2 1 0 0 1), (2 2 0 0 0)........ so on...... Total numbers of possible solutions are 70
Asked in: Microsoft Interview
1. Make a recursive function call to countSolutions(int n, int val)
2. Call this Solution function countSolutions(n-1, val-i) until n = 1 and val >=0 and then return 1.
Below is the implementation of above approach:
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.
- Program to find number of solutions in Quadratic Equation
- Number of solutions to Modular Equations
- Number of solutions of n = x + n ⊕ x
- Absolute difference between sum and product of roots of a quartic equation
- Number of ordered points pair satisfying line equation
- Recursive Practice Problems with Solutions
- Solutions to prevent Double-Spending of Bitcoins
- Queries to evaluate the given equation in a range [L, R]
- Finding sum of digits of a number until sum becomes single digit
- Minimum number of cubes whose sum equals to given number N
- Smallest odd number with even sum of digits from the given number N
- Difference between sum of the squares of first n natural numbers and square of sum
- Minimum value to be assigned to the elements so that sum becomes greater than initial sum
- Find maximum subset sum formed by partitioning any subset of array into 2 partitions with equal sum
- Sum and Product of nodes with value as even digit sum in Circular Linked List
- Sum of series formed by difference between product and sum of N natural numbers
- Maximize sum of remaining elements after every removal of the array half with greater sum
- Program for Sum of the digits of a given number
- Given an array A and a number x, check for pair in A with sum as x
- Root to leaf path sum equal to a given number
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.