全排列算法(递归)封装

1.使用方法:

string str = "abc";
Assemble assemble = new Assemble(str);
assemble.OnCreateOneGroup += (e) =>
{
    Console.WriteLine(e);
};
assemble.DoRank();


2.封装类:

/// <summary>
/// 将给定的字符数组,进行排列,得到不同顺序的排列结果
/// </summary>
public class Assemble
{
    /// <summary>
    /// 需要排序的字符数组
    /// </summary>
    private char[] _Source = null;
    /// <summary>
    /// 排序结果字符串数组
    /// </summary>
    private List<string> _Result = null;
    /// <summary>
    /// 获取排序成功一个数组是触发
    /// </summary>
    public Action<string> OnCreateOneGroup = null;
    /// <summary>
    /// 初始化
    /// </summary>
    /// <param name="Source">需要排列的字符数组</param>
    public Assemble(char[] Source)
    {
        if (Source == null || Source.Length <= 0)
            throw new Exception("传入的字符数组,不能为空");
        _Source = Source;
        _Result = new List<string>();
    }
    /// <summary>
    /// 初始化
    /// </summary>
    /// <param name="Source">需要排列的字符串</param>
    public Assemble(string Source)
    {
        if (string.IsNullOrEmpty(Source))
            throw new Exception("传入的字符串,不能为空");
        _Source = Source.ToArray();
        _Result = new List<string>();
    }
    /// <summary>
    /// 执行排列
    /// </summary>
    public void DoRank()
    {
        Rank(_Source, 0, _Source.Length - 1);
    }
    /// <summary>
    /// 排列方法
    /// </summary>
    /// <param name="source">源字符数组</param>
    /// <param name="start">开始位置</param>
    /// <param name="end">结束位置</param>
    private void Rank(char[] source, int start, int end)
    {
        int i;
        if (start > end)
        {
            StringBuilder builder = new StringBuilder(100);
            for (i = 0; i <= end; i++)
            {
                builder.Append(source[i]);
            }
            string result = builder.ToString();
            _Result.Add(result);
            if (OnCreateOneGroup != null)
            {
                OnCreateOneGroup(result);
            }
        }
        else
        {
            for (i = start; i <= end; i++)
            {
                Swap(ref source[start], ref source[i]);
                Rank(source, start + 1, end);
                //当一次排列结束,返回的时候再还原
                Swap(ref source[start], ref source[i]);
            }
        }
    }
    /// <summary>
    /// 交换字符位置
    /// </summary>
    private void Swap(ref char a, ref char b)
    {
        char temp = a;
        a = b;
        b = temp;
    }
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值