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

效果

相关推荐
lixww.cn5 小时前
ASP.NET Core MVC
c#·mvc·.netcore
我是苏苏6 小时前
C#高级:常用的扩展方法大全
java·windows·c#
_Yhisken6 小时前
【读书笔记】万字浅析游戏场景中常见的渲染性能优化手段
游戏·unity·性能优化·图形渲染·gpu
ChoSeitaku6 小时前
Unity|小游戏复刻|见缝插针2(C#)
unity·c#·游戏引擎
lzhdim7 小时前
3、C#基于.net framework的应用开发实战编程 - 实现(三、二) - 编程手把手系列文章...
开发语言·c#·.net
SunkingYang7 小时前
C#编译报错: error CS1069: 未能在命名空间“System.Windows.Markup”中找到类型名“IComponentConnector”
c#·.net·错误·程序集·升级framework·error cs1069·error cs0538
秋月的私语7 小时前
c#启动程序时使用异步读取输出避免假死
java·前端·c#
H CHY9 小时前
二维数组一
开发语言·数据结构·c++·算法·青少年编程·c#·动态规划
lshzdq10 小时前
【设计模式】访问者模式(Visitor Pattern): visitor.visit(), accept()
设计模式·c#·访问者模式
王维志11 小时前
浅谈Unity中Canvas的三种渲染模式
unity·游戏引擎