Combine algorithm

5 篇文章 0 订阅

Get combines by recursion, low performance.



class Program
    {
        /// <summary>
        /// Print all combines of C(n)(Left)
        /// </summary>
        /// <param name="left">which is not used</param>
        /// <param name="result">the results</param>
        /// <param name="n">combine number</param>
        private void Combine(ref string left, ref string result, int n)
        {
            if (left == null)
            {
                throw new ArgumentNullException("left");
            }
            if (result == null)
            {
                throw new ArgumentNullException("result");
            }
            if (n < 0)
            {
                throw new ArgumentNullException("n");
            }

            if (0 == n)
            {
                Console.Write("(");
                for (int i = 0; i < result.Length; i++)
                {
                    Console.Write(result[i]);
                    if (i < result.Length -1)
                    {
                        Console.Write(",");
                    }
                }
                Console.Write(") ");
            }
            else if (n <= left.Length)
            {
                // Retrieve the data
                result += left[0];
                string tmp_left = left.Substring(1);
                // Try to get the left n-1 data
                // a-> ab-> abc
                Combine(ref tmp_left, ref result, n - 1);

                // Pop the corrupted data
                // abc-> ab
                result = result.Substring(0, result.Length - 1);

                // Re-get data from left candidates  
                // ab-> ab? (?=defg)
                Combine(ref tmp_left, ref result, n);
            }
            else
            {
                return;
            }
        }


        static void TestCase1()
        {
            // string WORDS = "abcdefghijklmnopqrstuvwxyz";
            string WORDS = "abcdefg";
            Program p = new Program();
            string result = string.Empty;
            for (int i = 1; i <= WORDS.Length; i++)
            {
                try
                {
                    p.Combine(ref WORDS, ref result, i);
                    Console.WriteLine();
                    //Console.ReadLine();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }

        static void Main(string[] args)
        {
            TestCase1();
        }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值