在C#中生成两个数组的所有可能组合(不重复),可以使用递归或迭代的方法。下面我将提供一种使用递归的方法和一种使用迭代的方法,并给出详细的实例源代码。
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
int[] array1 = { 1, 2 };
int[] array2 = { 3, 4 };
List<List<int>> combinations = GenerateCombinations(array1, array2);
// 打印所有组合
foreach (var combination in combinations)
{
Console.WriteLine(string.Join(", ", combination));
}
}
static List<List<int>> GenerateCombinations(int[] array1, int[] array2)
{
List<List<int>> result = new List<List<int>>();
GenerateCombinationsHelper(array1, array2, new List<int>(), 0, 0, result);
return result;
}
static void GenerateCombinationsHelper(int[] array1, int[] array2, List<int> current, int index1, int index2, List<List<int>> result)
{
if (index1 == array1.Length && index2 == array2.Length)
{
result.Add(new List<int>(current));
return;
}
if (index1 < array1.Length)
{
current.Add(array1[index1]);
GenerateCombinationsHelper(array1, array2, current, index1 + 1, index2, result);
current.RemoveAt(current.Count - 1);
}
if (index2 < array2.Length)
{
current.Add(array2[index2]);
GenerateCombinationsHelper(array1, array2, current, index1, index2 + 1, result);
current.RemoveAt(current.Count - 1);
}
}
}
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
int[] array1 = { 1, 2 };
int[] array2 = { 3, 4 };
List<List<int>> combinations = GenerateCombinations(array1, array2);
// 打印所有组合
foreach (var combination in combinations)
{
Console.WriteLine(string.Join(", ", combination));
}
}
static List<List<int>> GenerateCombinations(int[] array1, int[] array2)
{
List<List<int>> result = new List<List<int>>();
Queue<List<int>> queue = new Queue<List<int>>();
queue.Enqueue(new List<int>());
while (queue.Count > 0)
{
List<int> current = queue.Dequeue();
if (current.Count == Math.Max(array1.Length, array2.Length))
{
result.Add(current);
continue;
}
if (current.Count < array1.Length)
{
List<int> nextCombination = new List<int>(current);
nextCombination.Add(array1[current.Count]);
queue.Enqueue(nextCombination);
}
if (current.Count < array2.Length)
{
List<int> nextCombination = new List<int>(current);
nextCombination.Add(array2[current.Count]);
queue.Enqueue(nextCombination);
}
}
return result;
}
}
这两种方法都可以生成两个数组的所有可能组合,选择使用哪种方法取决于个人偏好和实际需求。递归方法通常更易理解,但可能在数组较大时导致栈溢出。迭代方法使用队列来避免栈溢出的问题,但可能稍微复杂一些。
源代码获取:公众号回复消息【code:40850
】