生成字符数组的所有排列

编程入门 行业动态 更新时间:2024-10-27 00:25:26
本文介绍了生成字符数组的所有排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在阅读了很多生成字符串排列的帖子之后,我尝试用Java编写它。 1)让第一个字符开始与组合中剩余的字符进行交换。

After reading so many post of "generating permutation of string", I tried to write it in Java. 1) Take the first character start swapping with rest of the character in the combination.

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

But when I tried to implement it using recursion it gave me only two string for a string of length 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个字符串。

I am expecting 6 string to be printed.

预期: 123, 132, 213, 231, 312, 321

expected: 123, 132, 213, 231, 312, 321

推荐答案

方法 printPermutation 是递归的核心。它没有正确捕获开始和结束索引。这很重要,因为你试图交换块

The method printPermutation is the core of your recursion. It doesn't capture the start and end indices properly. This is important because you are trying to swap in chunks

以下更改应该可以使它工作。

Following change should make it work.

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; }

更多推荐

生成字符数组的所有排列

本文发布于:2023-11-30 10:11:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649612.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   排列   字符

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!