从给定字符串打印按字典顺序排序的子集

时间:2015-03-28 13:05:37

标签: algorithm sorting combinatorics

对于ex - 如果字符串是" abc",答案应该是 a ab abc ac b bc c(只应出现一组字符中按字典顺序排列的最小组合) 我已经解决了这个问题但是对于包含15个或更多字符的字符串,需要花费很多时间。如何减少算法的运行时间? 这里,n是字符串的长度。 这是我的代码:

            int n = int.Parse(Console.ReadLine());
            var str = Console.ReadLine();
            string coll = string.Empty;
            coll = coll + " " + str[0];
            for (int j = 1; j < n; j++)
            {
                var items = coll.Split(' ');
                foreach (var item in items)
                {
                    coll = coll + " " + item+str[j];
                }
            }
            var tt = coll.Split(' ').OrderBy(a => a);
            foreach (var item in tt)
                if (!string.IsNullOrEmpty(item))
                    Console.WriteLine(item);

1 个答案:

答案 0 :(得分:1)

对于长度为n的字符串,有2 ^ n个可能的子集。如果需要打印每个子集,则无法克服指数复杂性。