给定一个字符串str ,任务是打印str的所有排列。
就排列的顺序而言,排列是一组对象的全部或一部分的排列。
例如,单词“ bat”和“ tab”代表相似的三个字母单词的两个不同的排列(或排列)。
例子:
Input: str = “abc”
Output: abc acb bac bca cba cab
Input: str = “bat”
Output: bat bta abt atb tba tab
方法:编写一个递归函数,该函数将生成字符串的所有排列。终止条件为传递的字符串为空时,在这种情况下,该函数将返回一个空的ArrayList。
下面是上述方法的实现:
Java
// Java implementation of the approach
import java.util.ArrayList;
public class GFG {
// Utility function to print the contents
// of the ArrayList
static void printArrayList(ArrayList arrL)
{
arrL.remove("");
for (int i = 0; i < arrL.size(); i++)
System.out.print(arrL.get(i) + " ");
}
// Function to returns the arraylist which contains
// all the permutation of str
public static ArrayList getPermutation(String str)
{
// If string is empty
if (str.length() == 0) {
// Return an empty arraylist
ArrayList empty = new ArrayList<>();
empty.add("");
return empty;
}
// Take first character of str
char ch = str.charAt(0);
// Take sub-string starting from the
// second character
String subStr = str.substring(1);
// Recurvise call
ArrayList prevResult = getPermutation(subStr);
// Store the generated permutations
// into the resultant arraylist
ArrayList Res = new ArrayList<>();
for (String val : prevResult) {
for (int i = 0; i <= val.length(); i++) {
Res.add(val.substring(0, i) + ch + val.substring(i));
}
}
// Return the resultant arraylist
return Res;
}
// Driver code
public static void main(String[] args)
{
String str = "abc";
printArrayList(getPermutation(str));
}
}
C#
// C# implementation of the approach
using System.Collections.Generic;
using System;
class GFG
{
// Utility function to print the contents
// of the ArrayList
static void printArrayList(List arrL)
{
arrL.Remove("");
for (int i = 0; i < arrL.Count; i++)
Console.Write(arrL[i] + " ");
}
// Function to returns the arraylist which contains
// all the permutation of str
public static List getPermutation(String str)
{
// If string is empty
if (str.Length == 0)
{
// Return an empty arraylist
List empty = new List();
empty.Add("");
return empty;
}
// Take first character of str
char ch = str[0];
// Take sub-string starting from the
// second character
String subStr = str.Substring(1);
// Recurvise call
List prevResult = getPermutation(subStr);
// Store the generated permutations
// into the resultant arraylist
List Res = new List();
foreach (String val in prevResult)
{
for (int i = 0; i <= val.Length; i++)
{
Res.Add(val.Substring(0, i) + ch + val.Substring(i));
}
}
// Return the resultant arraylist
return Res;
}
// Driver code
public static void Main(String[] args)
{
String str = "abc";
printArrayList(getPermutation(str));
}
}
// This code has been contributed by 29AjayKumar
输出:
abc bac bca acb cab cba