How to get all the unique n-long combinations of a set of duplicatable elements?

前端 未结 5 1919
难免孤独
难免孤独 2020-12-21 08:48

I have found many solutions giving a collection elements combined in all possible orders but they all use every element just once in every result while I need them to be tr

5条回答
  •  隐瞒了意图╮
    2020-12-21 08:59

    You can use a depth first search:

    class Program
    {
        private static string[] letters = {"a", "b", "c"};
        private static void dfs(string accum, int depth)
        {
            if (depth == 0)
            {
                System.Console.WriteLine(accum);
                return;
            }
            foreach (string c in letters)
                dfs(accum + c, depth - 1);
        }
        public static void Main()
        {
            int depth = 2; //Number of letters in each result
            dfs("", depth);
            System.Console.ReadLine();
        }
    }
    


    Output:

    aa
    ab
    ac
    ba
    bb
    bc
    ca
    cb
    cc
    

提交回复
热议问题