我有一个程序可以打印字符串数组中所有可能的组合。屏幕上的打印效果很好。但是,当我将其添加到列表中时,所有列表成员都会反映最后生成的组合。所以,我不确定发生了什么。请看下面的代码。
class Program
{
static List<string[]> list = new List<string[]>();
static void combinationUtil(string[] arr, string[] data,
int start, int end,
int index, int r)
{
// Current combination is
// ready to be printed,
// print it
if (index == r)
{
list.Add(data);
for (int j = 0; j < r; j++)
{
Console.Write(data[j] + " ");
}
Console.WriteLine("");
return;
}
// replace index with all
// possible elements. The
// condition "end-i+1 >=
// r-index" makes sure that
// including one element
// at index will make a
// combination with remaining
// elements at remaining positions
for (int i = start; i <= end &&
end - i + 1 >= r - index; i++)
{
data[index] = arr[i];
combinationUtil(arr, data, i + 1,
end, index + 1, r);
}
}
// The main function that prints
// all combinations of size r
// in arr[] of size n. This
// function mainly uses combinationUtil()
static void printCombination(string[] arr,
int n, int r)
{
// A temporary array to store
// all combination one by one
string[] data = new string[r];
// Print all combination
// using temprary array 'data[]'
combinationUtil(arr, data, 0,
n - 1, 0, r);
}
// Driver Code
static public void Main()
{
string[] arr = { "string-1", "string-2", "string-3", "string-4" };
int r = 2;
int n = arr.Length;
printCombination(arr, n, r);
foreach (var item in list)
{
Console.WriteLine(item[0]+" "+item[1]);
}
}
}以下是输出

发布于 2020-10-07 22:32:16
我找到了一个方法来做到这一点。但是,我不确定这是否是唯一和最好的方法。如果你有任何其他更好的方法,请回答。下面是我如何做到这一点的。
list.Add(new string[2] { data[0], data[1] });发布于 2020-10-07 22:30:13
这是一个使用List的解决方案。请注意每个list.Add()之前的string[] uniquePair = new string[2];。
class Program
{
static List<string[]> list = new List<string[]>();
// Driver Code
static public void Main()
{
string[] arr = { "string-1", "string-2", "string-3", "string-4" };
int r = 2;
for (int i = 0; i < arr.Length; i++)
{
for (int j = i + 1; j < arr.Length; j++)
{
string[] uniquePair = new string[2];
uniquePair[0] = arr[i];
uniquePair[1] = arr[j];
list.Add(uniquePair);
}
}
foreach (string[] pair in list)
{
Console.WriteLine($"{ pair[0] } + { pair[1] }");
}
Console.ReadKey(true);
}
}输出:
string-1 + string-2
string-1 + string-3
string-1 + string-4
string-2 + string-3
string-2 + string-4
string-3 + string-4https://stackoverflow.com/questions/64244559
复制相似问题