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 小时前
C# 本地项目引用失效与恢复全攻略
开发语言·c#·visual studio
清风与日月2 小时前
c# 上位机作为控制端与下位机通信方式
单片机·嵌入式硬件·c#
B0URNE3 小时前
【Unity基础详解】Unity3D全程学习路线
学习·unity·游戏引擎
烛阴4 小时前
从零开始掌握C#核心:变量与数据类型
前端·c#
yue0085 小时前
C# 生成指定位数的编号
开发语言·c#
红黑色的圣西罗5 小时前
C# List.Sort方法总结
开发语言·c#
一步一个foot-print7 小时前
[Unity Shader Base] RayMarching in Cloud Rendering
unity·游戏引擎
ithinking1107 小时前
kotlin 集成 unity
unity·android studio
夏霞8 小时前
c# ASP.NET Core SignalR 客户端配置自动重连次数
c#·.netcore