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

 效果

相关推荐

  1. 实现组合型枚举

    2024-04-29 07:28:03       14 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-29 07:28:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-29 07:28:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-29 07:28:03       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-29 07:28:03       20 阅读

热门阅读

  1. 在 Ubuntu 下使用 clash-for-linux-backup

    2024-04-29 07:28:03       12 阅读
  2. 如何使用 MySQL Workbench 远程连接到 MySQL 服务器

    2024-04-29 07:28:03       12 阅读
  3. DSP开发实战教程--#pragma CODE_SECTION使用技巧

    2024-04-29 07:28:03       14 阅读
  4. 代谢组数据分析五:溯源分析

    2024-04-29 07:28:03       15 阅读
  5. GitHub 异常——无法连接22端口:Connection timed out

    2024-04-29 07:28:03       12 阅读
  6. 如何在小程序中添加图片和视频

    2024-04-29 07:28:03       17 阅读
  7. 如何利用GitHub Actions自动化你的开发流程

    2024-04-29 07:28:03       10 阅读
  8. Vue

    Vue

    2024-04-29 07:28:03      11 阅读