zoukankan      html  css  js  c++  java
  • C#全排列

    C#写个全排列数组,例如{123}采用递归方法:有两种方式,

    1)逐个增加数字:

     

    代码
           int[] a = new int[3] { 123 };
            
    private void button1_Click(object sender, EventArgs e)
            {
                
    for (int i = 0; i < 3; i++)
                {
                    
    string b;

                    b 
    = a[i].ToString();
                    count(b, 
    1);
                }
            }
            
    private void count(string numarray, int n)
            {
                
    if (n < 3)
                {
                    
    for (int i = 0; i < 3; i++)
                    {
                        
    string aa = a[i].ToString();

                        
    if (!numarray.Contains(aa)) //如果不包含这个数字,添加这个数字到数组
                        {
                            
    string tempstring = numarray;
                            numarray 
    = numarray + aa;
                            n
    ++;
                            count(numarray, n);
                            
    //递归完,注意恢复数组原样!!!!!!!!
                            numarray = tempstring;
                            n
    --;
                        }
                    }
                }
                
    else//n=3,打印输出
                {
                    print(numarray);
                }
            }

    2)通过交换数组中的元素:

    代码
           int[] a = new int[3] { 1, 2, 3 };
            private void button2_Click(object sender, EventArgs e)
            {
                perm(a, 
    02);
            }
            
    private void perm(int[] list, int i, int n)
            {
                
    int j;

                
    if (i == n)
                {
                    listprint(list);//
    打印其中一种排列组合
                }
                
    else
                {
                    
    for (j = i; j <= n; j++)
                    {
                        SWAP(
    ref list[i], ref list[j]);
                        perm(list, i 
    + 1, n);
                        SWAP(
    ref list[i], ref list[j]);//数组一定要复原!!!!!
                    }
                }
            }
            
    private void SWAP(ref int a, ref int b)
            {
                
    int c = a;
                a 
    = b;
                b 
    = c;
            }
  • 相关阅读:
    web前端笔记1
    前端与后台交互所需技术
    js的HTML属性操作
    浮动塌陷
    前端与后端的交互(定义接口)
    AjAX(第3章 Ajax的简单例子(Ajax+PHP)
    AjAX(简单概要介绍)
    Bootstrap 学习之js插件(折叠(collapse)插件)
    Net core 项目 EF CodeFist 多重外键约束问题
    对VS 2017中ASP.NET Core项目解决:Add-Migration : 无法将“Add-Migration”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。
  • 原文地址:https://www.cnblogs.com/king1302217/p/1641295.html
Copyright © 2011-2022 走看看