Palabras de longitud K que se pueden formar a partir de caracteres dados sin repetición

Dado un entero k y una string str que consta de alfabetos ingleses en minúsculas, la tarea es contar cuántas palabras de k caracteres (con o sin significado) se pueden formar a partir de los caracteres de str cuando no se permite la repetición.
Ejemplos: 
 

Entrada: str = “cat”, k = 3 
Salida:
Las palabras requeridas son “cat”, “cta”, “act”, “atc”, “tca” y “tac”.
Entrada: str = «geeksforgeeks», k = 3 
Salida: 840 
 

Enfoque: cuente el número de caracteres distintos en str y guárdelo en cnt , ahora la tarea es organizar k caracteres a partir de cnt , es decir, n P r = n. / (n – r)! .
A continuación se muestra la implementación del enfoque anterior: 
 

C++

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the required count
int findPermutation(string str, int k)
{
    bool has[26] = { false };
 
    // To store the count of distinct characters in str
    int cnt = 0;
 
    // Traverse str character by character
    for (int i = 0; i < str.length(); i++) {
 
        // If current character is appearing
        // for the first time in str
        if (!has[str[i] - 'a']) {
 
            // Increment the distinct character count
            cnt++;
 
            // Update the appearance of the current character
            has[str[i] - 'a'] = true;
        }
    }
 
    long long int ans = 1;
 
    // Since P(n, r) = n! / (n - r)!
    for (int i = 2; i <= cnt; i++)
        ans *= i;
 
    for (int i = cnt - k; i > 1; i--)
        ans /= i;
 
    // Return the answer
    return ans;
}
 
// Driver code
int main()
{
    string str = "geeksforgeeks";
    int k = 4;
    cout << findPermutation(str, k);
 
    return 0;
}

Java

// Java implementation of the approach
import java.util.*;
 
class solution
{
// Function to return the required count
static int findPermutation(String str, int k)
{
    boolean[] has = new boolean[26];
    Arrays.fill(has,false);
 
    // To store the count of distinct characters in str
    int cnt = 0;
 
    // Traverse str character by character
    for (int i = 0; i < str.length(); i++) {
 
        // If current character is appearing
        // for the first time in str
        if (!has[str.charAt(i) - 'a'])
        {
 
            // Increment the distinct character count
            cnt++;
 
            // Update the appearance of the current character
            has[str.charAt(i) - 'a'] = true;
        }
    }
 
    int ans = 1;
 
    // Since P(n, r) = n! / (n - r)!
    for (int i = 2; i <= cnt; i++)
        ans *= i;
 
    for (int i = cnt - k; i > 1; i--)
        ans /= i;
 
    // Return the answer
    return ans;
}
 
// Driver code
public static void main(String args[])
{
    String str = "geeksforgeeks";
    int k = 4;
    System.out.println(findPermutation(str, k));
 
}
}
// This code is contributed by
// Sanjit_prasad

Python3

# Python3 implementation of the approach
import math as mt
 
# Function to return the required count
def findPermutation(string, k):
 
    has = [False for i in range(26)]
 
    # To store the count of distinct
    # characters in str
    cnt = 0
 
    # Traverse str character by character
    for i in range(len(string)):
         
        # If current character is appearing
        # for the first time in str
        if (has[ord(string[i]) - ord('a')] == False):
 
            # Increment the distinct
            # character count
            cnt += 1
 
            # Update the appearance of the
            # current character
            has[ord(string[i]) - ord('a')] = True
         
    ans = 1
 
    # Since P(n, r) = n! / (n - r)!
    for i in range(2, cnt + 1):
        ans *= i
 
    for i in range(cnt - k, 1, -1):
        ans //= i
 
    # Return the answer
    return ans
 
# Driver code
string = "geeksforgeeks"
k = 4
print(findPermutation(string, k))
 
# This code is contributed
# by Mohit kumar 29

C#

// C# implementation of the approach
 
using System;
 
class solution
{
// Function to return the required count
static int findPermutation(string str, int k)
{
    bool []has = new bool[26];
     
    for (int i = 0; i < 26 ; i++)
        has[i] = false;
 
    // To store the count of distinct characters in str
    int cnt = 0;
 
    // Traverse str character by character
    for (int i = 0; i < str.Length; i++) {
 
        // If current character is appearing
        // for the first time in str
        if (!has[str[i] - 'a'])
        {
 
            // Increment the distinct character count
            cnt++;
 
            // Update the appearance of the current character
            has[str[i] - 'a'] = true;
        }
    }
 
    int ans = 1;
 
    // Since P(n, r) = n! / (n - r)!
    for (int i = 2; i <= cnt; i++)
        ans *= i;
 
    for (int i = cnt - k; i > 1; i--)
        ans /= i;
 
    // Return the answer
    return ans;
}
 
// Driver code
public static void Main()
{
    string str = "geeksforgeeks";
    int k = 4;
    Console.WriteLine(findPermutation(str, k));
 
}
// This code is contributed by Ryuga
}

PHP

<?php
// PHP implementation of the approach
 
// Function to return the required count
function findPermutation($str, $k)
{
    $has = array();
     
    for ($i = 0; $i < 26; $i++)
    {
        $has[$i]= false;
    }
     
    // To store the count of distinct characters in $str
    $cnt = 0;
 
    // Traverse $str character by character
    for ($i = 0; $i < strlen($str); $i++)
    {
 
        // If current character is appearing
        // for the first time in $str
        if ($has[ord($str[$i]) - ord('a')] == false)
        {
 
            // Increment the distinct character count
            $cnt++;
 
            // Update the appearance of the current character
            $has[ord($str[$i]) - ord('a')] = true;
        }
    }
 
    $ans = 1;
 
    // Since P(n, r) = n! / (n - r)!
    for ($i = 2; $i <= $cnt; $i++)
        $ans *= $i;
 
    for ($i = $cnt - $k; $i > 1; $i--)
        $ans /= $i;
 
    // Return the answer
    return $ans;
}
 
// Driver code
$str = "geeksforgeeks";
$k = 4;
echo findPermutation($str, $k);
 
 
// This code is contributed by ihritik
?>

Javascript

<script>
      // JavaScript implementation of the approach
      // Function to return the required count
      function findPermutation(str, k) {
        var has = new Array(26);
 
        for (var i = 0; i < 26; i++) has[i] = false;
 
        // To store the count of distinct characters in str
        var cnt = 0;
 
        // Traverse str character by character
        for (var i = 0; i < str.length; i++) {
          // If current character is appearing
          // for the first time in str
 
          if (!has[str[i].charCodeAt(0) - "a".charCodeAt(0)]) {
            // Increment the distinct character count
            cnt++;
 
            // Update the appearance of the current character
            has[str[i].charCodeAt(0) - "a".charCodeAt(0)] = true;
          }
        }
 
        var ans = 1;
 
        // Since P(n, r) = n! / (n - r)!
        for (var i = 2; i <= cnt; i++) ans *= i;
 
        for (var i = cnt - k; i > 1; i--) ans /= i;
 
        // Return the answer
        return ans;
      }
 
      // Driver code
      var str = "geeksforgeeks";
      var k = 4;
      document.write(findPermutation(str, k));
    </script>
Producción: 

840

 

Publicación traducida automáticamente

Artículo escrito por Vivek.Pandit y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *