博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Write a program to print all permutations of a given string
阅读量:4032 次
发布时间:2019-05-24

本文共 1404 字,大约阅读时间需要 4 分钟。

Write a program to print all permutations of a given string

A permutation, also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation.

Source: Mathword()

Below are the permutations of string ABC.

ABC, ACB, BAC, BCA, CAB, CBA

Here is a solution using backtracking.

  • C/C++
  • Python
# Python program to print all permutations with# duplicates allowed# Function to swap valuesdef swap(a,l,r):    t = a[l]    a[l] = a[r]    a[r] = t    return adef toList(string):    List = []    for x in string:        List.append(x)    return Listdef toString(List):    return ''.join(List)# Function to print permutations of string# This function takes three parameters:# 1. String# 2. Starting index of the string# 3. Ending index of the string.def permute(a, l, r):    if l==r:        print toString(a)    else:        for i in xrange(l,r+1):            a = swap(a,l,i)            permute(a, l+1, r)            a = swap(a,l,i) # backtrack# Driver program to test the above functionstring = "ABC"n = len(string)a = toList(string)permute(a, 0, n-1)# This code is contributed by Bhavya Jain

Output:
ABCACBBACBCACBACAB

Algorithm Paradigm: Backtracking
Time Complexity:  O(n*n!)

Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem.

转载地址:http://yihbi.baihongyu.com/

你可能感兴趣的文章
linux config
查看>>
linux insmod error -1 required key invalid
查看>>
linux kconfig配置
查看>>
linux不同模块completion通信
查看>>
linux printf获得时间戳
查看>>
C语言位扩展
查看>>
linux dump_backtrace
查看>>
linux irqdebug
查看>>
git 常用命令
查看>>
linux位操作API
查看>>
snprintf 函数用法
查看>>
uboot.lds文件分析
查看>>
uboot start.s文件分析
查看>>
没有路由器的情况下,开发板,虚拟机Ubuntu,win10主机,三者也可以ping通
查看>>
本地服务方式搭建etcd集群
查看>>
安装k8s Master高可用集群
查看>>
忽略图片透明区域的事件(Flex)
查看>>
忽略图片透明区域的事件(Flex)
查看>>
AS3 Flex基础知识100条
查看>>
Flex动态获取flash资源库文件
查看>>