字符串数组的组合 [英] Combinations of string arrays

查看:125
本文介绍了字符串数组的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

我有一个长度为3的字符串数组.该数组只是{"A","B","C"}.我已经摸索了一段时间,以了解如何为此打印所有组合.

只是数组的大小不会变化,所以即使为循环嵌入3 for循环也不是成功的解决方案. GRRR.

我想打印出所有3个字母的组合,即ABC,CAB等,输出字符串中没有字母重复.这种情况下总共有6个.对于其他人,我得到了数组长度的阶乘.

欢迎任何建议,并感谢您可能收到的任何帮助.

Hi there,

I have a string array of length 3. The array is just {"A", "B", "C"}. I have been scratching my head a while in how to possible print out all the combinations for this.

Just to not the size of array can vary so embedding 3 for loops is not a successful solution even though it works great. GRRR.

I want to print out all the 3 letter combos i.e ABC, CAB etc with no letter repition in the output string. There are 6 in total for this case. For others I get the factorial for the array length.

Any suggestions are welcome and thanks in advance for any hel that may be received

推荐答案

我想打印出所有3个字母的组合,即ABC,CAB等,而没有输出字符串中的字母重复.在这种情况下,总共有6个字符.对于其他情况,我得到了数组长度的阶乘." aka排列.

您可以查看LINQ + Recursion的实现(递归中的智能"多循环),如下所示:

"I want to print out all the 3 letter combos i.e ABC, CAB etc with no letter repition in the output string. There are 6 in total for this case. For others I get the factorial for the array length." aka Permutation.

You can review LINQ+Recursion implementation(a la "smart" multiloop in recursion), like this:

public static IEnumerable<string> GetPermutation(string s)
{
   if (s.Length > 1) {
      return from c in s
             from p in GetPermutation(s.Remove(s.IndexOf(c), 1))
             select c+p;
   } else {
      return new string[] { s };
   }
}



来自 http://stackoverflow.com/questions/774457/combination-generator-in-linq [



Code from http://stackoverflow.com/questions/774457/combination-generator-in-linq[


进行递归:递归将完成这项工作.
Go recursive: recursion would do the job.


如果您不特别担心速度和空间问题,最简单的方法是使用递归.

基本上按此伪代码的顺序进行操作:

If you aren''t particularly worried about speed and space issues, the simplest way to do it would be to use recursion.

Basically something on the order of this pseudo-code:

print_all_combinations_of( input_array ) {

   size = input_array.count

   if ( size == 1 ) {
   
       print input_array[0] + "\n"
 
   } else {

       for ( i = 0 ; i < size; i++ ) {

           print input_array[i]

           array_without_element_i = new array( input_array ) 

           array_without_element_i.remove_element_at(i)

           print_all_combinations_of ( array_without_element_i )

       }

   }

}


这篇关于字符串数组的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆