📜  数字的不同排列

📅  最后修改于: 2021-06-25 13:43:31             🧑  作者: Mango

给定整数N ,任务是打印数字N的所有不同排列。

例子:

方法:请按照以下步骤解决问题:

  • 初始化一个空字符串以存储N的等效字符串表示形式。
  • 初始化Map,将字符串的每个字符转换为整数并将其存储为列表。
  • 使用内置的Python函数itertools替换此列表。 permutations()。
  • 初始化另一个列表,例如newList。
  • 遍历列表的排列,如果permutation(list)不在newList中,则将此列表追加到newList
  • 初始化一个空字符串s =“” ,另一个空列表说permuteList。
  • 遍历列表newlist和每个列表,执行以下操作:
    • 遍历列表并将每个元素添加到字符串s中
    • 遍历后,将字符串转换为整数。
    • 将此整数附加到permuteList
  • permuteList的值打印为可能的不同排列。

下面是上述方法的实现:

Python3
# Python3 program for the above approach
  
from itertools import permutations
  
# Utility function to print
# all distinct permutations
def uniquePermutationsUtil(permute):
    
    p = []
      
    # Traverse the list permute[]
    for i in permute:
        
        # Convert this permutation to list
        permutelist = list(i)
          
        # Append this list to p
        p.append(permutelist)
  
    # Stores unique permutations
    newlist = []
      
    # Traverse list p[]
    for i in p:
        
        # If permutation is
        # not in newlist
        if i not in newlist:
            newlist.append(i)
  
    # Initialize empty list
    permutelist = []
      
    # Traverse the list newlist[]
    for i in newlist:
        
        # Initialize empty string
        s = ""
          
        # Traversing in element list
        for j in i:
            
            # Convert each
            # element to string
            s = s + str(j)
              
        # Convert string to integer
        s = int(s)
          
        # Append the unique
        # permutation to permutelist
        permutelist.append(s)
          
    # Print all distinct permutations 
    print(*permutelist)
      
# Function to print all 
# distinct permutations
def uniquePermutations(N):
    
    # Stores equivalent string
    # representation of N
    num = str(N)
  
    # Convert each character to
    # integer and store in the list
    lis = list(map(int, num))
      
    # Built in method to store all
    # permuations of the list
    permute = permutations(lis)
      
    # Print unique permutations
    uniquePermutationsUtil(permute)
  
# Driver Code
  
# Given value of N
N = 7668
  
# Function call to find all
# distinct permutations of N
uniquePermutations(N)


输出:
7668 7686 7866 6768 6786 6678 6687 6876 6867 8766 8676 8667

时间复杂度: O(N * N!)
辅助空间: O(N * N!)