您的位置:首页 > 其它

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

2006-11-01 19:19 429 查看
我要得到的是所有字符的排列组合,那么,我每次从所有字符中取出一个字符。然后我去先得到剩下字符的所有的排列组合,那么最后在这些所有的排列组合前面加上我取出来的这个数,那不就是得到了所有以我取出的这个字符开头的所有组合序列么?
最后我把所有字符中的每一个字符都让它打一次开头,也就是都先取出来一次,那么不就是所有的组合都实现了么?
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

Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=881284  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string system class c
相关文章推荐