LoginSignup
0
0

More than 3 years have passed since last update.

順列 C#

Posted at

順列 C#

using System;
using System.Collections.Generic;

namespace Permutation
{
    class Program
    {
        static void Main(string[] args)
        {
            new Program();
        }

        public Program()
        {
            List<int> data = new List<int> { 1, 2, 3, 4 };
            List<List<int>> perm = GetPermutation(data);
            foreach (List<int> p in perm) {
                Console.WriteLine(string.Join(",", p));
            }
        }

        private List<List<int>> GetPermutation(List<int> data)
        {
            List<List<int>> perm = new List<List<int>>();
            if (data.Count == 0) {
                perm.Add(data);
                return perm;
            }

            for (int i = 0; i < data.Count; i++) {
                int head = data[i];

                List<int> dataCopy = new List<int>(data);
                dataCopy.RemoveAt(i);
                List<List<int>> childPerm = GetPermutation(dataCopy);
                foreach (List<int> child in childPerm) {
                    child.Insert(0, head);
                    perm.Add(child);
                }
            }
            return perm;
        }
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0