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

效果

相关推荐
专注VB编程开发20年1 小时前
AI 生成C# WinForm 窗体 = 目前就是垃圾
开发语言·人工智能·c#
z落落2 小时前
C# 泛型接口和泛型类+泛型约束
开发语言·c#
阿正的梦工坊2 小时前
【Rust】08-集合类型、字符串与迭代器入门
开发语言·rust·c#
FuckPatience3 小时前
C# 使用泛型协变将派生类类型替换为基类类型
开发语言·c#
guygg883 小时前
C# 生成中间带 Logo 头像的二维码
开发语言·c#
Java面试题总结3 小时前
C#12 中的 Using Alias
开发语言·windows·c#
加号33 小时前
【C#】 ASCII 码转字符串技术解析
开发语言·c#
2601_961875245 小时前
高考真题word版下载|2025高考全科真题可编辑文档
c#·word·ar·vr·mr·高考·oneflow
RReality5 小时前
【Unity UGUI】血条 / 进度条(HP Bar)
ui·unity·游戏引擎·图形渲染
阿正的梦工坊6 小时前
【Rust】09-泛型、Trait 与生命周期基础
开发语言·rust·c#