Permutation of an array, with repetition, in Java

前端 未结 4 1092
名媛妹妹
名媛妹妹 2021-01-12 01:47

There are some similar questions on the site that have been of some help, but I can\'t quite nail down this problem, so I hope this is not repetitive.

This is a home

4条回答
  •  长情又很酷
    2021-01-12 02:12

    Here is c# version to generate the permutations of given string with repetitions:

    (essential idea is - number of permutations of string of length 'n' with repetitions is n^n).

    string[] GetPermutationsWithRepetition(string s)
            {
                s.ThrowIfNullOrWhiteSpace("s");
                List permutations = new List();
                this.GetPermutationsWithRepetitionRecursive(s, "",
                    permutations);
                return permutations.ToArray();
            }
            void GetPermutationsWithRepetitionRecursive(string s, string permutation, List permutations)
            {
                if(permutation.Length == s.Length)
                {
                    permutations.Add(permutation);
                    return;
                }
                for(int i =0;i

    Below are the corresponding unit tests:

    [TestMethod]
            public void PermutationsWithRepetitionTests()
            {
                string s = "";
                int[] output = { 1, 4, 27, 256, 3125 };
                for(int i = 1; i<=5;i++)
                {
                    s += i;
                    var p = this.GetPermutationsWithRepetition(s);
                    Assert.AreEqual(output[i - 1], p.Length);
                }
            }
    

提交回复
热议问题