Unity 递归实现数字不重复的排列组合

实现

复制代码
private void Permutation(List<int> num, int leftIndex, List<string> strs)
{
    if (leftIndex < num.Count)
    {
        for (int rightIndex = leftIndex; rightIndex < num.Count; rightIndex++)
        {
            Swap(num, leftIndex, rightIndex);
            Permutation(num, leftIndex + 1, strs);
            Swap(num, rightIndex, leftIndex);
        }
    }
    else
    {
        string s = string.Empty;
        for (int i = 0; i < num.Count; i++)
        {
            s += num[i].ToString();
            if (i < num.Count - 1)
                s += "→";
        }
        strs.Add(s);
    }
}
void Swap(List<int> num, int leftIndex, int rightIndex)
{
    int temp = num[leftIndex];
    num[leftIndex] = num[rightIndex];
    num[rightIndex] = temp;
}

示例

复制代码
List<int> num = new List<int>() { 1, 2 };
Permutation(num);
num = new List<int>() { 1, 2, 3 };
Permutation(num);

private void Permutation(List<int> num)
{
    List<string> strs = new List<string>();
    Permutation(num, 0, strs);

    string strNum = string.Empty;
    for (int i = 0; i < num.Count; i++)
    {
        strNum += num[i].ToString();
        if (i < num.Count - 1)
            strNum += ",";
    }
    Debug.Log(strNum + " 排列组合共 " + strs.Count + " 组");
    for (int i = 0; i < strs.Count; i++)
        Debug.Log(strs[i] + "\n");
}

效果

相关推荐
程序员老乔2 分钟前
Java 新纪元 — JDK 25 + Spring Boot 4 全栈实战(二):Valhalla落地,值类型如何让电商DTO内存占用暴跌
java·spring boot·c#
祝大家百事可乐20 分钟前
嵌入式——02 数据结构
c++·c#·硬件工程
mxwin1 小时前
Unity Shader UI 流光效果完全推导指南
ui·unity·游戏引擎·shader·uv
我是唐青枫1 小时前
深入理解 C#.NET TaskScheduler:为什么大量使用 Work-Stealing
c#·.net
唯情于酒3 小时前
net core web api 使用log4net
c#·.net core
SunnyDays10113 小时前
C# 实战:快速查找并高亮 Word 文档中的文字(普通查找 + 正则表达式)
开发语言·c#
人工智能AI技术3 小时前
Qwen3.5-Plus登顶|C#集成通义千问,高并发服务实战优化
人工智能·c#
WarPigs4 小时前
编辑器/AB包资源校验工具
unity
呆呆敲代码的小Y4 小时前
Unity+AI 用一句话制作完整小游戏:飞翔的牛马【AI纯添加-0手工代码】
人工智能·游戏·unity·游戏引擎·游戏制作·unityai·一句话制作游戏
SunnyDays10114 小时前
如何使用 C# 在 Word 文档中插入超链接 (含文本与图片链接)
开发语言·c#