4342024 2023-10-24 15:51 采纳率: 46.7%
浏览 14
已结题

c#输出所有排列组合问题,数据处理

A篮中有1 2两个球 B篮中有3 4两个球,从AB篮子中任选一个,输出所有的组合,可以用迭代for循环输出。
如果我不知道有多少个篮子,然后我选择从所有篮子中各选一个,这个时候应该怎么做,怎么输出所有组合?
比如4个篮子的时候,5个篮子的时候,要求只调用这个函数就可以输出。

  • 写回答

7条回答 默认 最新

  • 社区专家-Monster-XH 2023-10-24 15:51
    关注

    基于Monster 组和GPT的调写:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    class Program
    {
        static void Main()
        {
            // 假设有四个篮子,每个篮子里的字符串可以不同
            List<string[]> baskets = new List<string[]>
            {
                new string[] { "a1", "a2" },
                new string[] { "b1", "b2" },
                new string[] { "c1", "c2" },
                new string[] { "d1", "d2" }
                // 你可以继续添加更多篮子
            };
    
            List<string> combination = new List<string>();
            
            GenerateCombinations(baskets, combination, 0);
    
            // 如果想演示更多篮子,只需向'baskets'列表添加更多的字符串数组即可。
        }
    
        static void GenerateCombinations(List<string[]> baskets, List<string> currentCombination, int basketIndex)
        {
            if (basketIndex == baskets.Count) // 如果所有篮子都已处理
            {
                Console.WriteLine(string.Join(", ", currentCombination));
                return;
            }
    
            string[] currentBasket = baskets[basketIndex];
            for (int i = 0; i < currentBasket.Length; i++)
            {
                List<string> newCombination = new List<string>(currentCombination);
                newCombination.Add(currentBasket[i]);
                GenerateCombinations(baskets, newCombination, basketIndex + 1);
            }
        }
    }
    
    
    

    GenerateCombinations函数开始于第一个篮子(索引0),并为该篮子中的每个球创建一个新的组合列表。然后,它递归地调用自己,这次是为下一个篮子(索引1),如此类推,直到处理完所有篮子。每次达到篮子列表的末尾时,它就会打印出当前的组合。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(6条)

报告相同问题?

问题事件

  • 系统已结题 11月1日
  • 已采纳回答 10月24日
  • 创建了问题 10月24日

悬赏问题

  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置