gpt4 book ai didi

java - 生成字符数组的所有排列

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:07:12 26 4
gpt4 key购买 nike

看了那么多“生成字符串的排列”的帖子,我试着用Java写。1) 取第一个字符开始与组合中的其余字符交换。

但是当我尝试使用递归实现它时,它只给了我两个长度为 3 的字符串:(。

public static void main(String[] args) {
char a[]= "123".toCharArray();
printPermutation(a,0);

}
private static void printPermutation(char[] a, int i) {
if(i==a.length-1)
System.out.println(new String(a));
else{
for(int x=i+1;x<a.length;x++)
{
swap(a,i,x);
printPermutation(a,x );
swap(a,i,x);
}
}
}
private static void swap(char[] a, int i, int x) {
char t=a[i];
a[i]=a[x];
a[x]=t;
}

我希望打印 6 个字符串。

预计:123、132、213、231、312,321

最佳答案

printPermutation 方法是递归的核心。它没有正确捕获 startend 索引。这很重要,因为您正在尝试交换 block

以下更改应该可以使其正常工作。

public static void main(String[] args) {
char a[]= "123".toCharArray();
printPermutation(a, 0, a.length);
}

private static void printPermutation(char[] a, int startIndex, int endIndex) {
if (startIndex == endIndex)//reached end of recursion, print the state of a
System.out.println(new String(a));
else {
//try to move the swap window from start index to end index
//i.e 0 to a.length-1
for (int x = startIndex; x < endIndex; x++) {
swap(a, startIndex, x);
printPermutation(a, startIndex + 1, endIndex);
swap(a, startIndex, x);
}
}
}

private static void swap(char[] a, int i, int x) {
char t = a[i];
a[i] = a[x];
a[x] = t;
}

关于java - 生成字符数组的所有排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38878671/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com