The question is fairly simple. There is a set {2,4,6}. The expected answer is all possible permutations to get the number 6. So, the answer will be:-
{ 2,2,2} , {2,4} , {4,2} , {6}
What I've tried:-
I'm trying to approach this problem using the popular "coin change" question. But in coin change permutations are not there. Means {2,4} and {4,2} are regarded as same. Here's my code. It doesn't account permutations.
public static int NumberOfWays(int sum)
{
int [][] memMatrix = new int [7][sum+1];
for (int i = 2 ; i <= 6 ; i += 2)
{
for (int j = 0 ; j <= sum ; j += 2)
{
if (i == 2)
{
//using only 2 , there is only 1 way to get the sum
memMatrix[i][j] = 1;
}
else if ( i > j)
{
//if total sum is less than the newly used denomination , then the number of ways will always remain same
memMatrix[i][j] = memMatrix[i - 2][j];
}
else
{
//if this is the case then need to calculate without using the denomination + using the denomination
memMatrix[i][j] = memMatrix[i - 2][j] + memMatrix[i][j - i];
}
}
}
for (int i = 2 ; i <= 6 ; i += 2)
{
for (int j = 2 ; j <= sum ; j += 2)
{
System.out.print(memMatrix[i][j]+" ");
}
System.out.print("\n");
}
return memMatrix[6][sum];
}
Here's the output that I get along with the matrix. How can I account permutations also?
1 1 1
1 2 2
1 2 3
The number of ways to get 6 = 3