Interview Questions

183. print all the numbers that will sum up to n .......

Microsoft Interview Questions and Answers


(Continued from previous question...)

183. print all the numbers that will sum up to n .......

Question:
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 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 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