[C#] C#查找字符串的所有排列组合 →→→→→进入此内容的聊天室

来自 , 2020-11-23, 写在 C#, 查看 129 次.
URL http://www.code666.cn/view/aaebdb8b
  1.  // 1. remove first char
  2. // 2. find permutations of the rest of chars
  3. // 3. Attach the first char to each of those permutations.
  4. //     3.1  for each permutation, move firstChar in all indexes to produce even more permutations.
  5. // 4. Return list of possible permutations.
  6.  
  7. public string[] FindPermutations(string word)
  8.         {
  9.             if (word.Length == 2)
  10.             {
  11.                 char[] _c = word.ToCharArray();
  12.                 string s = new string(new char[] { _c[1], _c[0] });
  13.                 return new string[]
  14.                 {
  15.                     word,
  16.                     s
  17.                 };
  18.             }
  19.  
  20.             List<string> _result = new List<string>();
  21.  
  22.             string[] _subsetPermutations = FindPermutations(word.Substring(1));
  23.             char _firstChar = word[0];
  24.             foreach (string s in _subsetPermutations)
  25.             {
  26.                 string _temp = _firstChar.ToString() + s;
  27.                 _result.Add(_temp);
  28.                 char[] _chars = _temp.ToCharArray();
  29.                 for (int i = 0; i < _temp.Length - 1; i++)
  30.                 {
  31.                     char t = _chars[i];
  32.                     _chars[i] = _chars[i + 1];
  33.                     _chars[i + 1] = t;
  34.                     string s2 = new string(_chars);
  35.                     _result.Add(s2);
  36.                 }
  37.             }
  38.             return _result.ToArray();
  39.         }                
  40. //csharp/6443

回复 "C#查找字符串的所有排列组合"

这儿你可以回复上面这条便签

captcha