Найдите количество M символьных слов, в которых повторяется хотя бы один символ

Опубликовано: 13 Января, 2022

Даны два целых числа N и M , задача состоит в том, чтобы подсчитать общее количество слов длиной M символов, образованных заданными N различными символами, так чтобы в словах хотя бы один символ повторялся более одного раза.
Примеры:

Input: N = 3, M = 2
Output:
Suppose the characters are {‘a’, ‘b’, ‘c’}
All 2 length words that can be formed with these characters
are “aa”, “ab”, “ac”, “ba”, “bb”, “bc”, “ca”, “cb” and “cc”.
Out of these words only “aa”, “bb” and “cc” have
at least one character repeated more than once.
Input: N = 10, M = 5
Output: 69760

Рекомендуется: сначала попробуйте свой подход в {IDE}, прежде чем переходить к решению.

Approach:
Total number of M character words possible from N characters, total = NM
Total number of M character words possible from N characters where no character repeats itself, noRepeat = NPM
So, total words where at least a single character appear more than once is total – noRepeat i.e. NMNPM.
Below is the implementation of the above approach:

C++

 `// C++ implementation for the above approach``#include ``#include ``using` `namespace` `std;` `// Function to return the``// factorial of a number``int` `fact(``int` `n)``{``    ``if` `(n <= 1)``        ``return` `1;``    ``return` `n * fact(n - 1);``}` `// Function to return the value of nPr``int` `nPr(``int` `n, ``int` `r)``{``    ``return` `fact(n) / fact(n - r);``}` `// Function to return the total number of``// M length words which have at least a``// single character repeated more than once``int` `countWords(``int` `N, ``int` `M)``{``    ``return` `pow``(N, M) - nPr(N, M);``}` `// Driver code``int` `main()``{``    ``int` `N = 10, M = 5;``    ``cout << (countWords(N, M));``    ``return` `0;``}` `// This code is contributed by jit_t`

Java

 `// Java implementation of the approach``class` `GFG {` `    ``// Function to return the``    ``// factorial of a number``    ``static` `int` `fact(``int` `n)``    ``{``        ``if` `(n <= ``1``)``            ``return` `1``;``        ``return` `n * fact(n - ``1``);``    ``}` `    ``// Function to return the value of nPr``    ``static` `int` `nPr(``int` `n, ``int` `r)``    ``{``        ``return` `fact(n) / fact(n - r);``    ``}` `    ``// Function to return the total number of``    ``// M length words which have at least a``    ``// single character repeated more than once``    ``static` `int` `countWords(``int` `N, ``int` `M)``    ``{``        ``return` `(``int``)Math.pow(N, M) - nPr(N, M);``    ``}` `    ``// Driver code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``int` `N = ``10``, M = ``5``;``        ``System.out.print(countWords(N, M));``    ``}``}`

Python3

 `# Python3 implementation for the above approach` `# Function to return the``# factorial of a number``def` `fact(n):` `    ``if` `(n <``=` `1``):``        ``return` `1``;``    ``return` `n ``*` `fact(n ``-` `1``);` `# Function to return the value of nPr``def` `nPr(n, r):` `    ``return` `fact(n) ``/``/` `fact(n ``-` `r);` `# Function to return the total number of``# M length words which have at least a``# single character repeated more than once``def` `countWords(N, M):` `    ``return` `pow``(N, M) ``-` `nPr(N, M);` `# Driver code``N ``=` `10``; M ``=` `5``;``print``(countWords(N, M));` `# This code is contributed by Code_Mech`

C#

 `// C# implementation of the approach``using` `System;` `class` `GFG``{``    ` `    ``// Function to return the``    ``// factorial of a number``    ``static` `int` `fact(``int` `n)``    ``{``        ``if` `(n <= 1)``            ``return` `1;``        ``return` `n * fact(n - 1);``    ``}` `    ``// Function to return the value of nPr``    ``static` `int` `nPr(``int` `n, ``int` `r)``    ``{``        ``return` `fact(n) / fact(n - r);``    ``}` `    ``// Function to return the total number of``    ``// M length words which have at least a``    ``// single character repeated more than once``    ``static` `int` `countWords(``int` `N, ``int` `M)``    ``{``        ``return` `(``int``)Math.Pow(N, M) - nPr(N, M);``    ``}` `    ``// Driver code``    ``static` `public` `void` `Main ()``    ``{``        ``int` `N = 10, M = 5;``        ``Console.Write(countWords(N, M));``    ``}``}` `// This code is contributed by ajit.`

Javascript

 `// javascript implementation of the approach` `      ` `    ``// Function to return the``    ``// factorial of a number``    ` `    ``function` `fact(n)``    ``{``        ``if` `(n <= 1)``            ``return` `1;``        ``return` `n * fact(n - 1);``    ``}``  ` `    ``// Function to return the value of nPr``    ` `    ``function` `nPr( n,  r)``    ``{``        ``return` `fact(n) / fact(n - r);``    ``}``  ` `    ``// Function to return the total number of``    ``// M length words which have at least a``    ``// single character repeated more than once``    ` `    ``function` `countWords( N,  M)``    ``{``        ``return` `Math.pow(N, M) - nPr(N, M);``    ``}``  ` `    ``// Driver code``        ``var` `N = 10 ;``        ``var` `M = 5;``        ``document.write(countWords(N, M));` `  ``// This code is contributed by bunnyram19.`
Output:
`69760`

Вниманию читателя! Не прекращайте учиться сейчас. Освойте все важные концепции DSA с помощью самостоятельного курса DSA по приемлемой для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .

Если вы хотите посещать живые занятия с отраслевыми экспертами, пожалуйста, обращайтесь к Geeks Classes Live и Geeks Classes Live USA.