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

效果

相关推荐
Traced back6 小时前
# C# + SQL Server 实现自动清理功能的完整方案:按数量与按日期双模式
开发语言·c#
JIes__7 小时前
Unity(二)——MonoBehavior中的重要内容
unity·游戏引擎
yj爆裂鼓手7 小时前
c#万能变量
开发语言·c#
不绝1917 小时前
C#进阶:委托
开发语言·c#
喜欢喝果茶.7 小时前
跨.cs 文件传值(C#)
开发语言·c#
就是有点傻7 小时前
C#中如何和欧姆龙进行通信的
c#
黑夜中的潜行者16 小时前
构建高性能 WPF 大图浏览器:TiledViewer 技术解密
性能优化·c#·.net·wpf·图形渲染
LongtengGensSupreme17 小时前
C# 中监听 IPv6 回环地址(Loopback Address)----socket和tcp
c#·ipv6 回环地址
就是有点傻17 小时前
C#中如何和西门子通信
开发语言·c#
海底星光17 小时前
c#进阶疗法 -jwt+授权
c#