导航

C#全排列

Posted on 2010-01-07 15:17  寒宵飞飞  阅读(1757)  评论(1编辑  收藏  举报

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