c#排列组合递归算法

从n个字符串中取m个字符的所有组合(无放回抽样)

数学原理

Cm=Cn-1m+Cn-1m-1

c#代码示例

using System;
using System.Collections.Generic;
using System.Text;

namespace Combination
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] Sample = new string[] { “0”, “1”, “2”, “3”, “4”, “5”,”6″,”7″,”8″,”9″,”a”,”b”,”c”,”d”,”e”,”f”,”g” };
            List<string> SampleList = new List<string>();
            SampleList.AddRange(Sample);
            List<string> result = getCombination(SampleList, 3);
            Console.Read();
        }
        static List<string> getCombination(List<string> SampleList, int m)
        {
            if (m == 1)
            {
                return SampleList;
            }
            List<string> result = new List<string>();
            if (SampleList.Count == m)
            {
                StringBuilder temp_sb = new StringBuilder();
                foreach (string s in SampleList)
                {
                    temp_sb.Append(s);
                }
                result.Add(temp_sb.ToString());
                Console.WriteLine(temp_sb.ToString());
                return result;
            }
            string temp_firstelement = SampleList[0];
            SampleList.RemoveAt(0);
            List<string> temp_samplist1 = new List<string>();
            temp_samplist1.AddRange(SampleList);
            List<string> temp_list1 = getCombination(temp_samplist1, m – 1);
            foreach (string s in temp_list1)
            {
                result.Add(temp_firstelement + s);
                Console.WriteLine(temp_firstelement + s);
            }       
            List<string> temp_samplist2 = new List<string>();
            temp_samplist2.AddRange(SampleList);
            List<string> temp_list2 = getCombination(temp_samplist2, m);
            result.AddRange(temp_list2);           
            return result;
        }
    }
}

SampleList的Count如果小于m的情况没有处理

    原文作者:递归算法
    原文地址: https://blog.csdn.net/sisistar/article/details/1523785
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞