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

效果

相关推荐
HonestGoat10 小时前
Unity3d之碰撞体设置
unity
Xin_ye1008612 小时前
C# 零基础到精通教程 - 第七章:面向对象编程(入门)——类与对象
开发语言·c#
rockey62712 小时前
AScript异步执行与await关键字
c#·.net·script·eval·expression·异步执行·动态脚本
程序leo源14 小时前
Qt窗口详解
开发语言·数据库·c++·qt·青少年编程·c#
月巴月巴白勺合鸟月半18 小时前
质本洁来还洁去,强于污淖陷文本
c#
那个村的李富贵18 小时前
Unity自适应文本提示框:从原理到实战
unity·游戏引擎
HonestGoat18 小时前
Unity3d之鼠标光标
unity
WarPigs18 小时前
Unity人物翻越功能
unity·游戏引擎
游乐码19 小时前
Unity基础(四)向量相关
游戏·unity·游戏引擎
Xin_ye1008619 小时前
C# 零基础到精通教程 - 第八章:面向对象编程(进阶)——继承与多态
开发语言·c#