217. Suppose you are given a function void NumberofSum(int n) , write a code such that will print all the numbers that will sum up to n
Microsoft Interview Questions and Answers
(Continued from previous question...)
217. Suppose you are given a function void NumberofSum(int n) , write a code such that will print all the numbers that will sum up to n
Question:
Suppose you are given a function void NumberofSum(int n) , write a code such that will print all the numbers that will sum up to n
For Ex.
n output
1 {1}
2 {(1,1) , (2)}
3 {(1,1,1), (1,2) , (3)}
4 {(1,1,1,1),(1,1,2),(1,3),(2,2) , (4)}
maybe an answer:
void NumSum(int targetSum, vector<int> v, int starVal, int partialSum)
{
if (partialSum == targetSum)
{
printf( "{");
for (int i=0; i < v.size(); i++)
{
printf ("%d , ", v[i]);
}
printf( "}");
return;
}
for (int i = startVal; i < targetSum;i++)
{
if (i+partialSum <= targetSum)
{
NumSum(targetSum, v.push(i), i, partialSum+i);
v.pop_back();
}
}
}
void NumberofSum(int n)
{
vector <int> v;
for (int i=1; i < n;i++)
{
printf("{");
NumSum(i , v, 1, 0);
printf("}\n");
v.clear();
}
}
(Continued on next question...)
Other Interview Questions
- Microsoft Interview questions in HR or recruiter Round
- 261. Remove intersections of two single linked list and make one linked list.....
- Given number 1,2,3,4,5,6,7,8,9 find all sets that sums up to 10.....
- Given 2 sorted linked lists - merge them .....
- 224. find out how many unique paths to the top right hand corner cell
- We have two sorted array.......
- 151. Print all possible palindromes(of length >2) for a given string.
- given a polynomial f(x) of degree n, i.e......
- 223. Find median of two sorted arrays.
- Given a set of words in a dictionary, write a program to group ....
- More...
|