动态规划算法来列举出所有可能的组合方法。具体步骤如下:
创建一个二维数组 dp,大小为 (N+1) x (B+1),其中 dp[i][j] 表示用数组 A 的前 i 个数字组成和为 j组合数。
初始化 dp[0][0] 为 1,表示用空集合组成和为 0 的组合数为 1。
遍历数组 A 的每个数字,记当前数字为 num。
4 对于 dp[i][j],有两种情况:
如果 j >= num,则可以选择使用当前数字 num,则 dp[i][j] = dp-1][j] + dp[i-1][j-num];
否则,不能使用当前数字 num,则 dp[i][j] = dp[i-1][j]。
最终,dp[N][B] 即为数组 A 中所有能组成和为 B 的组合数。
以下是使用 C# 实现的示例代码:
csharp public static<List<int>> GetCombinations(int[] A, int) { int N =.Length; int[,] dp = new int[N + 1, B + 1]; dp[0, 0] = 1;
for (int i = 1; i <= N; i++)
{
int num = A[i - 1];
for (int j = 0; j <= B;++)
{
dp[i, j] = dp[i - 1, j];
if (j >= num)
{
dp[i, j] += dp[i - 1, j - num];
}
}
}
List<List<int>> combinations = new List<List<int>>();
GetCombinationsHelper(A, B, N, dp new List<int>(), combinations);
return combinations;
}
private static void GetCombinationsHelper(int[] A, int B, int i, int[,] dp, List<int> current, List<List<int>> combinations) { if (B == 0) { combinations.Add(new List<int>(current)); return; }
if (i <= 0 || B < 0 || dp[i, B] == 0)
{
return;
}
if (dp[i, B] == dp[i - 1, B])
{
GetCombinationsHelper(A, B, i - 1, dp, current, combinations);
}
if (B >= A[i - 1] && dp[i, B] == dp - 1, B - A[i - 1]] + 1)
{
current.Add(A[i - 1]);
GetCombinationsHelper(A, B - A[i - 1], i - 1, dp, current, combinations);
current.RemoveAt(current.Count - 1);
}
}
您可以调用 `GetCombinations` 函数来获取数组 A 中所有能组成和为 B 的组合。以下是使用示例:
```csharp
int[] A = { 1, 2, , 4, 5 };
int B = 7;
List<List<int>> combinations = GetCombinations(A, B);
foreach (List<int> combination in combinations)
{
Console.WriteLine(string.Join(", ", combination));
}
请注意,由组合数量可能很大,输出所有组合可能会占用大量内存。建议在使用时谨慎选择数组 A 的大小和目标数字 B 的范围。
上一篇
发表评论