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");
}

效果

相关推荐
唐青枫3 小时前
别滥用 Task.Run:C# 异步并发实操指南
c#·.net
我好喜欢你~10 小时前
C#---StopWatch类
开发语言·c#
NRatel13 小时前
亚马逊S3的使用简记(游戏资源发布更新)
游戏·unity·amazon s3
一阵没来由的风14 小时前
拒绝造轮子(C#篇)ZLG CAN卡驱动封装应用
c#·can·封装·zlg·基础封装·轮子
SmalBox19 小时前
【渲染流水线】[几何阶段]-[屏幕映射]以UnityURP为例
unity·渲染
一枚小小程序员哈20 小时前
基于微信小程序的家教服务平台的设计与实现/基于asp.net/c#的家教服务平台/基于asp.net/c#的家教管理系统
后端·c#·asp.net
Eternity_GQM1 天前
【Word VBA Zotero 引用宏错误分析与改正指南】【解决[21–23]参考文献格式插入超链接问题】
开发语言·c#·word
cimeo1 天前
【C 学习】06-算法&程序设计举例
c#
百锦再1 天前
.NET 的 WebApi 项目必要可配置项都有哪些?
java·开发语言·c#·.net·core·net
WYH2872 天前
C#控制台输入(Read()、ReadKey()和ReadLine())
开发语言·c#