using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Combo("一二三四五六七八九十").Where(x => x.Length >= 2 && x.Length <= 7).ToList().ForEach(x => Console.WriteLine(x));
        }        static IEnumerable<string> Combo(string s)
        {
            foreach (var x in (Enumerable.Range(1, Convert.ToInt32(Math.Pow((double)2, (double)s.Length)) - 1)))
            {
                string r = "";
                var x1 = x;
                for (int i = 0; i < s.Length; i++ )
                {
                    r += x1 % 2 == 0 ? "" : s[i].ToString();
                    x1 /= 2;
                }
                yield return r;
            }
        }
    }
}这段代码是字符串"一二三四五六七八九十"全组合之后再选出长度为2到7的字串,问题是如果字符串再长一些程序的运行速度很慢,要改为组成7字的字串后就不再继续进行组合,求高人帮忙~~~~~

解决方案 »

  1.   


      static IEnumerable<string> Combo(string s)加个参数呗,串够长了就直接return
      

  2.   

    http://topic.csdn.net/u/20090217/21/f41ed9f6-f929-451c-a5c9-80d2e408422a.html自己改改吧
      

  3.   

    最简单的就是上面的方法,你分别调3次啊。Combo("一二三四五六七")
    Combo("二三四五六七八")
    ...
      

  4.   

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Combo("一二三四五六七八九十", 2, 7).ToList().ForEach(x => Console.WriteLine(x));
            }        static IEnumerable<string> Combo(string s, int min, int max)
            {
                for (int i = min; i <= max; i++)
                { 
                    foreach (var item in _Combo(s, i)) yield return item;
                }
            }        static IEnumerable<string> _Combo(string s, int len)
            {
                int[] pos = new int[len];
                for (int i = 0; i < len; i++) pos[i] = i;
                while (pos[0] < s.Length - len)
                {
                    string str = "";
                    for (int i = 0; i < len; i++) str += s[pos[i]];
                    for (int i = len - 1; i >= 0; i--)
                    {
                        if (pos[i] < s.Length - len + i)
                        {
                            pos[i]++;
                            for (int j = i + 1; j <= len - 1; j++)
                            {
                                pos[j] = pos[i] + j - i;
                            }
                            break;
                        }
                        else
                        {
                            continue;
                        }
                    }
                    yield return str;
                }
            }
        }
    }