获取数组中特定长度的所有子数组

本文关键字:数组 获取 | 更新日期: 2023-09-27 18:09:26

我想获得c#中数组子集的帮助。所有其他的例子都不能帮助我。

我想要得到一个特定大小的数组的所有子集。

例如,如果输入数组为{1,2,3,4},并且我希望所有子集的大小为3,所有的独特的子集{1,2,3},{1,2,4},{2、3、4},{1,3,4}必须返回。

我是c#新手,任何形式的帮助都是非常感谢的。

获取数组中特定长度的所有子数组

查看本文。用各种编程语言的示例详细描述了这一点。我觉得没有必要复制别人的解决方案,所以我将把这个作为一个链接,让你从许多例子中选择,这应该有助于你

从n

返回k个元素的所有组合的算法

听起来像是家庭作业....

由于我假定大小是可变的,因此您将希望使用递归。比如:

    static void Main(string[] args)
    {
        int[] originalList = new int[] { 1, 2, 3, 4 };
        Stack<int> currentList = new Stack<int>();
        List<int[]> listOfSubsets = new List<int[]>();
        BuildListOfSubsets(originalList, listOfSubsets, 3, 0, currentList);
    }
    private static void BuildListOfSubsets(int[] originalList, List<int[]> listOfSubsets, int sizeOfSubsetList, int currentLevel, Stack<int> currentList)
    {
        if (currentList.Count == sizeOfSubsetList)
        {
            int[] copy = new int[sizeOfSubsetList];
            currentList.CopyTo(copy, 0);
            listOfSubsets.Add(copy);
        }
        else
            for (int ix = currentLevel; ix < originalList.Length; ix++)
            {
                currentList.Push(originalList[ix]);
                BuildListOfSubsets(originalList, listOfSubsets, sizeOfSubsetList, ix + 1, currentList);
                currentList.Pop();
            }
    }

结果将在listOfSubsets列表中。看看你是否能找到一个优化,让for循环早点结束。

如果您正在寻找LINQ解决方案,请尝试:

int[] originalList = { 1,2,1 };
var srcl = originalList.ToList();
List<List<int>> ans = Enumerable.Range(0, srcl.Count).SelectMany(start => Enumerable.Range(1, srcl.Count - start).Select(count => srcl.GetRange(start, count))).ToList();

如果你正在寻找一个更简单的解决方案,没有递归,那么这将有助于:

(这是打印所有子集的常见解决方案,要打印特定场景,例如只有长度为3的子集,使用最内层循环)

    class Program
    {
        static void Main(string[] args)
        {
            int[] arr = { 1, 2, 3, 4, 5 };
            int length = arr.Length;
            for (int start = 0; start < length; start++)
            {
                for (int end = start; end < length; end++)
                {
                    Console.Write("{");
                    // printing the subset, use this to add any condition, 
                    // like create a array and match the length, or anything
                    for (int print = start; print <= end; print++)
                    {
                        Console.Write(arr[print]);
                    }
                    Console.WriteLine("}");
                }
            }
        }
    }
相关文章: