Permute

順列(Permutation)を求めるメソッドPermuteを書いてみた。使わなかったけど折角なので載っけてみる。(ゴミ箱行きも勿体無いので)

        List<List<T>> Permute<T>(List<List<T>> permutationList, List<T> list, int k, int m)
        {
            if (k == m)
            {
                T[] array = new T[list.Count];

                list.CopyTo(array);
                permutationList.Add(new List<T>(array));
            }
            else
            {
                for (int i = k; i < m; i++)
                {
                    T a = list[k];
                    T b = list[i];
                    Swap<T>(ref a, ref b);
                    list[k] = a;
                    list[i] = b;

                    Permute(permutationList, list, k + 1, m);

                    a = list[k];
                    b = list[i];
                    Swap<T>(ref a, ref b);
                    list[k] = a;
                    list[i] = b;
                }
            }

            return permutationList;
        }

        void Swap<T>(ref T a, ref T b)
        {
            T tmp = a;
            a = b;
            b = tmp;
        }