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

效果

相关推荐
hez20102 小时前
用 .NET NativeAOT 构建完全 distroless 的静态链接应用
c#·.net·aot·.net core·native
幻想趾于现实3 小时前
C# Winform 入门(11)之制作酷炫灯光效果
开发语言·c#·winform
Eiceblue4 小时前
.NET用C#在PDF文档中添加、删除和替换图片
开发语言·pdf·c#·.net·idea
勘察加熊人4 小时前
c#和c++脚本解释器科学运算
开发语言·c++·c#
唐青枫4 小时前
dotnet 编译模式使用教程
c#·.net
du fei4 小时前
C# 窗体应用(.FET Framework) 与 visionpro 连接
开发语言·c#
anlog5 小时前
C#中为自定义控件设置工具箱图标
c#
benben0445 小时前
Unity3D仿星露谷物语开发34之单击Drop项目
游戏·ui·unity·游戏引擎
念心科道尊6 小时前
【Csharp】Winform客户端与服务器,局域网加密字符串与文件通信
运维·服务器·c#
爱凤的小光7 小时前
图漾相机——C#语言属性设置
开发语言·c#