How to find permutation of k in a given length?

前端 未结 6 683
小鲜肉
小鲜肉 2020-12-05 17:01

How can I find the permutations of k in a given length?

For example:

The word cat has 3 letters: How can I find all the permutations of 2 in the

6条回答
  •  情歌与酒
    2020-12-05 17:11

    Not the most efficient, but it works:

    public class permutation
    {
        public static List getPermutations(int n, string word)
        {
            List tmpPermutation = new List();
            if (string.IsNullOrEmpty(word) || n <= 0)
            {
                tmpPermutation.Add("");
            }
            else
            {
                for (int i = 0; i < word.Length; i++)
                {
                    string tmpWord = word.Remove(i, 1);
                    foreach (var item in getPermutations(n - 1, tmpWord))
                    {
                        tmpPermutation.Add(word[i] + item);
                    }
                }
            }
            return tmpPermutation;
        }
    }
    

提交回复
热议问题