【发布时间】:2017-11-13 07:24:45
【问题描述】:
这个问题很简单。有一个集合 {2,4,6}。预期的答案是得到数字 6 的所有可能排列。因此,答案将是:-
{ 2,2,2} , {2,4} , {4,2} , {6}
我尝试过的:-
我正在尝试使用流行的“硬币找零”问题来解决这个问题。但是在硬币变化排列中不存在。表示 {2,4} 和 {4,2} 被认为是相同的。这是我的代码。它不考虑排列。
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];
}
这是我与矩阵一起得到的输出。我如何也可以进行帐户排列?
1 1 1
1 2 2
1 2 3
The number of ways to get 6 = 3
【问题讨论】:
标签: sum set permutation dynamic-programming coin-change