📜  打印不同的排序排列,并在输入中允许重复

📅  最后修改于: 2021-04-24 18:09:37             🧑  作者: Mango

编写一个程序,以按排序的顺序打印给定字符串的所有不同排列。请注意,输入字符串可能包含重复的字符。
在数学中,置换的概念涉及将集合的所有成员按某种顺序或次序进行的动作,或者如果集合已经被排序,对其元素进行重新排列(重新排序),则此过程称为置换。
资料来源–维基百科
例子:

使用的概念:由长度为’n’的不同字符的字符串生成的字符串数等于’n!’。对任何给定的字符串排序,然后从字典上生成下一个更大的字符串,直到从这些字符得出最大的字典上的字符串为止。

脚步:

示例:考虑字符串“ ABCD”。
步骤1:对字符串排序。
步骤2:获得可以由该字符串形成的排列总数。
步骤3:打印排序后的字符串,然后循环(排列1)次,因为已经打印了第一个字符串。
步骤4:找到下一个更大的字符串,。
这是此问题的实现–

C++
// C++ program to print all permutations
// of a string in sorted order.
#include 
using namespace std;
 
// Calculating factorial of a number
int factorial(int n)
{
    int f = 1;
    for (int i = 1; i <= n; i++)
        f = f * i;
    return f;
}
 
// Method to find total number of permutations
int calculateTotal(string temp, int n)
{
    int f = factorial(n);
 
    // Building Map to store frequencies of
    // all characters.
    map hm;
    for (int i = 0; i < temp.length(); i++)
    {
        hm[temp[i]]++;
    }
 
    // Traversing map and
    // finding duplicate elements.
    for (auto e : hm)
    {
        int x = e.second;
        if (x > 1)
        {
            int temp5 = factorial(x);
            f /= temp5;
        }
        return f;
    }
}
 
static void nextPermutation(string &temp)
{
     
    // Start traversing from the end and
    // find position 'i-1' of the first character
    // which is greater than its successor.
    int i;
    for (i = temp.length() - 1; i > 0; i--)
        if (temp[i] > temp[i - 1]) break;
 
    // Finding smallest character after 'i-1' and
    // greater than temp[i-1]
    int min = i;
    int j, x = temp[i - 1];
    for (j = i + 1; j < temp.length(); j++)
        if ((temp[j] < temp[min]) and
            (temp[j] > x))
            min = j;
 
    // Swapping the above found characters.
    swap(temp[i - 1], temp[min]);
 
    // Sort all digits from position next to 'i-1'
    // to end of the string.
    sort(temp.begin() + i, temp.end());
 
    // Print the String
    cout << temp << endl;
}
 
void printAllPermutations(string s)
{
     
    // Sorting String
    string temp(s);
    sort(temp.begin(), temp.end());
 
    // Print first permutation
    cout << temp << endl;
 
    // Finding the total permutations
    int total = calculateTotal(temp, temp.length());
    for (int i = 1; i < total; i++)
    {
        nextPermutation(temp);
    }
}
 
// Driver Code
int main()
{
    string s = "AAB";
    printAllPermutations(s);
}
 
// This code is contributed by
// sanjeev2552


Java
// Java program to print all permutations of a string
// in sorted order.
import java.io.*;
import java.util.*;
 
class Solution {
 
  // Calculating factorial of a number
  static int factorial(int n) {
    int f = 1;
    for (int i = 1; i <= n; i++)
      f = f * i;
    return f;
  }
 
  // Method to print the array
  static void print(char[] temp) {
    for (int i = 0; i < temp.length; i++)
      System.out.print(temp[i]);
    System.out.println();
  }
 
  // Method to find total number of permutations
  static int calculateTotal(char[] temp, int n) {
    int f = factorial(n);
 
    // Building HashMap to store frequencies of
    // all characters.
    HashMap hm =
                     new HashMap();
    for (int i = 0; i < temp.length; i++) {
      if (hm.containsKey(temp[i]))
        hm.put(temp[i], hm.get(temp[i]) + 1);
      else
        hm.put(temp[i], 1);
    }
 
    // Traversing hashmap and finding duplicate elements.
    for (Map.Entry e : hm.entrySet()) {
      Integer x = (Integer)e.getValue();
      if (x > 1) {
        int temp5 = factorial(x);
        f = f / temp5;
      }
    }
    return f;
  }
 
  static void nextPermutation(char[] temp) {
 
    // Start traversing from the end and
    // find position 'i-1' of the first character
    // which is greater than its  successor.
    int i;
    for (i = temp.length - 1; i > 0; i--)
      if (temp[i] > temp[i - 1])
        break;
 
    // Finding smallest character after 'i-1' and
    // greater than temp[i-1]
    int min = i;
    int j, x = temp[i - 1];
    for (j = i + 1; j < temp.length; j++)
      if ((temp[j] < temp[min]) && (temp[j] > x))
        min = j;
 
    // Swapping the above found characters.
    char temp_to_swap;
    temp_to_swap = temp[i - 1];
    temp[i - 1] = temp[min];
    temp[min] = temp_to_swap;
 
    // Sort all digits from position next to 'i-1'
    // to end of the string.
    Arrays.sort(temp, i, temp.length);
 
    // Print the String
    print(temp);
  }
 
  static void printAllPermutations(String s) {
 
    // Sorting String
    char temp[] = s.toCharArray();
    Arrays.sort(temp);
 
    // Print first permutation
    print(temp);
 
    // Finding the total permutations
    int total = calculateTotal(temp, temp.length);
    for (int i = 1; i < total; i++)
      nextPermutation(temp);
  }
 
  // Driver Code
  public static void main(String[] args) {
    String s = "AAB";
    printAllPermutations(s);
  }
}


Python3
# Python3 program to print
# all permutations of a
# string in sorted order.
from collections import defaultdict
 
# Calculating factorial
# of a number
def factorial(n):
 
    f = 1
     
    for i in range (1, n + 1):
        f = f * i
    return f
 
# Method to find total
# number of permutations
def calculateTotal(temp, n):
 
    f = factorial(n)
 
    # Building Map to store
    # frequencies of all
    # characters.
    hm = defaultdict (int)
     
    for i in range (len(temp)):
        hm[temp[i]] += 1
    
    # Traversing map and
    # finding duplicate elements.
    for e in hm:
        x = hm[e]
        if (x > 1):
            temp5 = factorial(x)
            f //= temp5
        return f
 
def nextPermutation(temp):
     
    # Start traversing from
    # the end and find position
    # 'i-1' of the first character
    # which is greater than its successor
    for i in range (len(temp) - 1, 0, -1):
        if (temp[i] > temp[i - 1]):
            break
 
    # Finding smallest character
    # after 'i-1' and greater
    # than temp[i-1]
    min = i
    x = temp[i - 1]
    for j in range (i + 1, len(temp)):
        if ((temp[j] < temp[min]) and
            (temp[j] > x)):
            min = j
 
    # Swapping the above
    # found characters.
    temp[i - 1], temp[min] = (temp[min],
                              temp[i - 1])
 
    # Sort all digits from
    # position next to 'i-1'
    # to end of the string
    temp[i:].sort()
 
    # Print the String
    print (''.join(temp))
 
def printAllPermutations(s):
     
    # Sorting String
    temp = list(s)
    temp.sort()
 
    # Print first permutation
    print (''.join( temp))
 
    # Finding the total permutations
    total = calculateTotal(temp,
                           len(temp))
    for i in range (1, total):
        nextPermutation(temp)
 
# Driver Code
if __name__ == "__main__":
 
    s = "AAB"
    printAllPermutations(s)
 
# This code is contributed by Chitranayal


C#
// C# program to print all permutations
// of a string in sorted order.
using System;
using System.Collections.Generic;
 
class GFG
{
 
// Calculating factorial of a number
static int factorial(int n)
{
    int f = 1;
    for (int i = 1; i <= n; i++)
    f = f * i;
    return f;
}
 
// Method to print the array
static void print(char[] temp)
{
    for (int i = 0; i < temp.Length; i++)
    Console.Write(temp[i]);
    Console.WriteLine();
}
 
// Method to find total number of permutations
static int calculateTotal(char[] temp, int n)
{
    int f = factorial(n);
 
    // Building Dictionary to store frequencies 
    // of all characters.
    Dictionary hm = new Dictionary();
    for (int i = 0; i < temp.Length; i++)
    {
        if (hm.ContainsKey(temp[i]))
            hm[temp[i]] = hm[temp[i]] + 1;
        else
            hm.Add(temp[i], 1);
    }
 
    // Traversing hashmap and
    // finding duplicate elements.
    foreach(KeyValuePair e in hm)
    {
        int x = e.Value;
        if (x > 1)
        {
            int temp5 = factorial(x);
            f = f / temp5;
        }
    }
    return f;
}
 
static void nextPermutation(char[] temp)
{
 
    // Start traversing from the end and
    // find position 'i-1' of the first character
    // which is greater than its successor.
    int i;
    for (i = temp.Length - 1; i > 0; i--)
    if (temp[i] > temp[i - 1])
        break;
 
    // Finding smallest character after 'i-1'
    // and greater than temp[i-1]
    int min = i;
    int j, x = temp[i - 1];
    for (j = i + 1; j < temp.Length; j++)
    if ((temp[j] < temp[min]) && (temp[j] > x))
        min = j;
 
    // Swapping the above found characters.
    char temp_to_swap;
    temp_to_swap = temp[i - 1];
    temp[i - 1] = temp[min];
    temp[min] = temp_to_swap;
 
    // Sort all digits from position next to 'i-1'
    // to end of the string.
    Array.Sort(temp, i, temp.Length-i);
 
    // Print the String
    print(temp);
}
 
static void printAllPermutations(String s)
{
 
    // Sorting String
    char []temp = s.ToCharArray();
    Array.Sort(temp);
 
    // Print first permutation
    print(temp);
 
    // Finding the total permutations
    int total = calculateTotal(temp, temp.Length);
    for (int i = 1; i < total; i++)
    nextPermutation(temp);
}
 
// Driver Code
public static void Main(String[] args)
{
    String s = "AAB";
    printAllPermutations(s);
}
}
 
// This code is contributed by Rajput-Ji


输出:

AAB
ABA
BAA

时间复杂度: O(n * m),其中n是数组的大小,m是可能的排列数量。
辅助空间: O(n)。