From cc475a8b16b0e9323623c6532e114dceeb64353a Mon Sep 17 00:00:00 2001 From: chai Date: Mon, 21 Jun 2021 15:53:42 +0800 Subject: +recursions --- Assets/Algorithms/Recursion.cs | 63 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Assets/Algorithms/Recursion.cs (limited to 'Assets/Algorithms/Recursion.cs') diff --git a/Assets/Algorithms/Recursion.cs b/Assets/Algorithms/Recursion.cs new file mode 100644 index 0000000..30ebd8a --- /dev/null +++ b/Assets/Algorithms/Recursion.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using AlgorithmCollection; + +// 递归与分治算法 + +namespace AlgorithmCollection.Recursion +{ + + public static class RecursionHelper + { + + #region 全排列,返回数据的所有组合 + public static void Permutations(List data, ref List> perms) + { + if (perms == null) + perms = new List>(); + foreach(List perm in perms) + { + List p = new List(perm); + perms.Add(p); + } + } + + // 生成器形式,每次返回一个组合 + public static IEnumerable Permutations(List data) + { + foreach(var perm in _Permutations(data, 0, data.Count - 1)) + { + yield return perm; + } + } + + // 计算start~end范围内的全排列 + private static IEnumerable _Permutations(List data, int start , int end, List perm = null) + { + if(perm == null) + perm = new List(data.Count); + if(start == end) + { + perm.Add(data[start]); + yield return perm; + perm.RemoveAt(perm.Count - 1); + } + else + { + for (int i = start; i <= end; ++i) + { + perm.Add(data[i]); + Algorithms.Swap(ref data, start, i); + IEnumerator itor = _Permutations(data, start + 1, end, perm).GetEnumerator(); + while(itor.MoveNext()) + yield return itor.Current; + Algorithms.Swap(ref data, start, i); + perm.RemoveAt(perm.Count - 1); + } + } + } + #endregion + + } +} \ No newline at end of file -- cgit v1.1-26-g67d0