Interview Questions

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