显示字符串中所有字符的排列组合。

 我要得到的是所有字符的排列组合,那么,我每次从所有字符中取出一个字符。然后我去先得到剩下字符的所有的排列组合,那么最后在这些所有的排列组合前面加上我取出来的这个数,那不就是得到了所有以我取出的这个字符开头的所有组合序列么?
最后我把所有字符中的每一个字符都让它打一次开头,也就是都先取出来一次,那么不就是所有的组合都实现了么?
using System;
using System.Collections;

namespace MyNameSpace
{
 class GenerateWords
 {
  public static void Main()
  {
   ArrayList res = Generate_Permutations("abc");
   Console.WriteLine( "Count = " + res.Count);
   for(int i=0;i<res.Count;i++)
   {
    Console.WriteLine(res[i]);
   }
  }
  public static ArrayList Generate_Permutations(string word)
  {
   ArrayList result = new ArrayList();
   if(word.Length == 1)
   {
    result.Add(word);
    return result;
   }
   for(int i=0;i<word.Length;i++)
   {
    string shorter_word = word.Substring(0,i) + word.Substring(i+1,word.Length-i-1);
    ArrayList shorter_Permutations = Generate_Permutations(shorter_word);
    for(int j=0;j<shorter_Permutations.Count;j++)
    {
     string longer_word = word[i].ToString() + shorter_Permutations[j].ToString();
     result.Add(longer_word);
    }
   }
   return result;
  }
 }

另一种求排列组合,跟上面的要求不一样,不过经常有人问!

using System;
using System.Collections;

namespace AllCombinations
{
 class GenerateWords
 {
  public static void Main()
  {
   ArrayList res = Generate_Permutations("abcd");
   Console.WriteLine( "Count = " + res.Count);
   for(int i=0;i<res.Count;i++)
   {
    Console.WriteLine(res[i]);
   }
  }
  public static ArrayList Generate_Permutations(string word)
  {
   ArrayList result = new ArrayList();
   result.Add(word[word.Length-1]);
   if(word.Length <= 1)
    return result;
   for(int i=word.Length -2 ;i>=0;i--)
   {
    int count = result.Count;
    for(int j=0;j<count;j++)
    {
     result.Add(word[i].ToString() + result[j].ToString());
    }
    result.Add(word[i].ToString());
   }
   return result;
  }
 }
}

// The results is :
Count = 15
d
cd
c
bd
bcd
bc
b
ad
acd
ac
abd
abcd
abc
ab
a

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值