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

效果

相关推荐
gc_22991 小时前
C#测试调用OpenXml操作word文档的基本用法
c#·word·openxml
almighty274 小时前
C#海康车牌识别实战指南带源码
c#·海康车牌识别·c#实现车牌识别·车牌识别源码·c#车牌识别
极客柒7 小时前
Unity 塔防自用可视化路点寻路编辑器
unity·编辑器·游戏引擎
c#上位机7 小时前
wpf之TextBlock
c#·wpf
程序猿多布7 小时前
Unity AssetBundle详解
unity·assetbundle
萘柰奈12 小时前
Unity学习----【进阶】Addressables(二)--加载资源与打包及更新
学习·unity
almighty2716 小时前
C# WinForm分页控件实现与使用详解
c#·winform·分页控件·c#分页·winform分页
almighty2717 小时前
C#实现导入CSV数据到List<T>的完整教程
c#·csv·格式转换·c#导入数据·csv数据导入
lvcoc17 小时前
unity 接入火山引擎API,包括即梦AI
windows·unity·ai·火山引擎
程序猿多布18 小时前
Lua和C#比较
c#·lua