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

效果

相关推荐
yue0081 小时前
C# winform自定义控件
开发语言·c#
_Cherry|1 小时前
Unity按钮动态效果
unity·游戏引擎
_Cherry|2 小时前
Unity读取文件夹内容
unity·c#
lrh30253 小时前
Custom SRP - 15 Particles
unity·渲染管线·粒子·srp·扰动效果
张人玉3 小时前
C#通信精讲系列——C# 通讯编程基础(含代码实例)
开发语言·c#·c#通信
小熊熊知识库3 小时前
C# Ollama 实战聊天小案例实现
开发语言·c#
arron88994 小时前
WebApi 部署到win7 IIS详细步骤
c#
零点零一4 小时前
C# 的 out 参数:全面解析与最佳实践
c#
c#上位机4 小时前
halcon获取区域中心坐标以及面积——area_center
图像处理·计算机视觉·c#·halcon
Scout-leaf4 小时前
WPF新手村教程(一) - 走不出新手村别找我
c#·wpf