一个指定长度的数组,求指定个数组成的所有子集并打印出来!比如说:string[8],找出由3个元素组成的所有子集!

解决方案 »

  1.   

    参考: 字符串str,取n个字符的所有组合..
    //这个不用我改成你需要的String[]吧,上次有个家伙给他参考,非让我改成int[]public String[] GetAllCombination(String str,Int32 n)  //n < str.Length 
            {
                Int32[] state = new Int32[str.Length];
                Char[] chars = str.ToCharArray();
                List<String> list = new List<String>();            for (Int32 i = 0; i < n; i++)
                {
                    state[i] = 1;
                }
                for (Int32 i = n; i < state.Length; i++)
                {
                    state[i] = 0;
                }            list.Add(str.Substring(0,n));
                while (true)
                {
                    Boolean flag = true;
                    Int32 index = 0;
                    Int32 oneCount = 0;
                    Int32 zeroCount = 0;
                    StringBuilder sbuilder = new StringBuilder();                for(; index < state.Length - 1; index++)
                    {
                        if (state[index] == 1 && state[index + 1] == 0)
                        {
                            Int32 temp = state[index];
                            state[index] = state[index + 1];
                            state[index + 1] = temp;
                            break;
                        }
                    }                for (Int32 i = 0; i < index; i++)
                    {
                        if (state[i] == 0)
                            zeroCount++;
                        else
                            oneCount++;
                    }                for (Int32 i = 0; i < index; i++)
                    {
                        if (i < oneCount)
                            state[i] = 1;
                        else
                            state[i] = 0;
                    }                for (Int32 i = 0; i < chars.Length; i++) 
                    {
                        if (state[i] == 1)
                            sbuilder.Append(chars[i]);
                    }                list.Add(sbuilder.ToString());                for (Int32 i = 0; i < chars.Length - n; i++)
                    {
                        if (state[i] == 1)
                        {
                            flag = false;
                            break;
                        }
                    }
                    if (flag)
                        break;
                }            return list.ToArray();
            }