{///Console.WriteLine("{0}{1}{2}", c1[re。根据集合排列出所有可能组合。" />

根据集合排列出所有可能组合


一个国外论坛上看到的相近算法,很有点意思!

/// /// 集合所有排列 /// var c1 = new string[] { "L", "Z", "G", "H" }; /// SetAlgorithms.Arrangement(c1.Length, 3, (result, len) => { ///Console.WriteLine("{0}{1}{2}", c1[result[0]], c1[result[1]], c1[result[2]]); ///return true; /// }); ///


【根据集合排列出所有可能组合】
public static class SetAlgorithms { public delegate bool SetAlgorithmCallback(int[] result, int length); static bool CheckNM(int n, int m) { if (m > n || m < 0 || n < 0) { throw new ArgumentException(); }if (m == 0 || n == 0) return false; return true; }static bool Arrangement(int n, int rlen, int[] result, SetAlgorithmCallback callback) { if (rlen == result.Length) return callback(result, rlen); for (int i = 0; i < n; ++i) { bool skip = false; for (int j = 0; j < rlen; ++j) { if (result[j] == i) { skip = true; break; } }if (skip) continue; result[rlen] = i; if (!Arrangement(n, rlen + 1, result, callback)) return false; }return true; }public static void Arrangement(int n, int m, SetAlgorithmCallback callback) { if (!CheckNM(n, m)) return; var result = new int[m]; for (int i = 0; i < n; ++i) { result[0] = i; if (!Arrangement(n, 1, result, callback)) return; } } }



    推荐阅读