string1 = "ABC"
string2 = "DEF"
string3 = "GHIJ"
输出:"ADG","ADH","ADI","ADJ","AEG","AEH","AEI","AEJ","AFG","AFH","AFI","AFJ“,”AFI“,”AFJ“对于b和c使用递归的方法将是非常有帮助的..
发布于 2018-10-03 07:23:09
此方法不使用递归,但在我看来,它是生成所需排列的最简单方法。
static void permute(String... str)
{
char[][] chars = new char[str.length][];
for(int i=0; i<str.length; i++)
chars[i] = str[i].toCharArray();
int[] idx = new int[str.length];
char[] perm = new char[str.length];
for(int i=0; i<str.length; i++)
perm[i] = chars[i][0];
while(true)
{
System.out.println(new String(perm));
int k=str.length-1;
for(; k>=0; k--)
{
idx[k] += 1;
if(idx[k] < chars[k].length)
{
perm[k] = chars[k][idx[k]];
break;
}
idx[k] = 0;
perm[k] = chars[k][idx[k]];
}
if(k < 0) break;
}
}
测试:
public static void main(String[] args)
{
permute("ABC", "DEF", "GHIJ");
}
输出:
ADG
ADH
ADI
ADJ
AEG
AEH
AEI
<snip>
CFG
CFH
CFI
CFJ
https://stackoverflow.com/questions/52608204
复制相似问题