gpt4 book ai didi

string - 我的排列代码每次都打印 nPn 吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:15:30 26 4
gpt4 key购买 nike

所以我正在尝试编写一个代码,它将按照 nPr 方式打印出字符串的所有排列,其中 n 是字符串长度,r 是输入。它接受一个前缀和字符串,以及一个整数。除了每次打印 nPn 排列而不是 nPr 排列外,它会执行此操作。

public static void main(String[] args){
String x = "abcd";
permu("", x, 2);
}
public static void permu(String pre, String x, int r){
if(x.length() == 0)
System.out.println(pre.substring(0, r));
else{
for(int i = 0; i < x.length(); i++)
permu(pre + x.charAt(i), x.substring(0, i) + x.substring(i + 1, x.length()), r);
}
}

对于 r = 2,我希望它打印 ab、ac、ad、ba、bc、bd、ca、cb、cd、da、db、dc。但它会打印所有内容的两倍。

最佳答案

您必须将递归限制设置为r(现在是n)。大概是这样:

   if(x.length() == 0)
change to
if(pre.length() == r)

关于string - 我的排列代码每次都打印 nPn 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41639345/

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