gpt4 book ai didi

java - 通过递归查找 Char 数组中的字符序列

转载 作者:行者123 更新时间:2023-11-29 08:12:09 25 4
gpt4 key购买 nike

我有一个递归项目来查找 Char 数组的所有序列(或子集),这样每个字符都以相同的顺序出现。例如,对于数组 Char[] letters = {'A', 'B','C','D'}
单字母序列为“A”、“B”、“C”、“D”。
两个字母序列是"AB","AC","AD","BC","BD","CD"。
三个字母序列是"ABC","ABD","ACD","BCD"
四字母顺序为“ABCD”

现在我认为我使用下面的代码是在正确的轨道上,但是我得到了很多重复项。我真的很沮丧。如果有人能指出我正确的方向,我将不胜感激。

// print all subsets of the characters in s
public static void combinations(char[] array) { combinations("", array, 0); }

// print all subsets of the remaining elements, with given prefix
private static void combinations(String prefix, char[] array, int index) {

for(int i = index; i < array.length; i++)
{

System.out.println(prefix + array[i]);
}


if (index < array.length) {
for(int i = index; i < array.length; i++){
combinations(prefix + array[i], array, index+1);
}
}

}

为了澄清起见,删除我的编辑。

最佳答案

您似乎在这里使用了错误的变量:

combinations(prefix + array[i], array, index+1);

应该是i而不是index:

combinations(prefix + array[i], array, i+1);

输出:

ABCDABACADABCABDABCDACDBCBDBCDCD

Ideone: http://ideone.com/H4Okw

关于java - 通过递归查找 Char 数组中的字符序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7562366/

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