【发布时间】:2021-05-29 19:32:35
【问题描述】:
如果数组 a 包含完全相同的数字,则数组 a 是数组 b 的排列,因此:
a{ 3, 2, 4, 1, 5 } is permutation of b{ 1, 2, 3, 4, 5, 5 };
我写了这段代码:
int x4a[] = { 3, 2, 4, 1, 5 };
int x4b[] = { 1, 2, 3, 4, 5, 5 };
System.out.println(isPermutation(x4a, x4b));//Should return true
public static boolean isPermutation(int[] a, int[] b) {
return isPermutation(a, b, 0, 0);
}
public static boolean isPermutation(int[] a, int[] b, int indexA, int indexB) {
// This code will return true if the shorter array contains all the members of
// the longer array.
// In this case b will be compared to a
if (a.length < b.length) {
if (indexB == b.length - 1 && a[indexA] == b[indexB])
return true;
else if (a[indexA] == b[indexB])
isPermutation(a, b, 0, indexB + 1);
else if (indexA == a.length - 1 && a[indexA] != b[indexB])
return false;
else if (indexA < a.length - 1 && a[indexA] != b[indexB])
isPermutation(a, b, indexA + 1, indexB);
} else {
if (indexA == a.length - 1 && a[indexA] == b[indexB])
return true;
else if (a[indexA] == b[indexB])
isPermutation(a, b, 0, indexA + 1);
else if (indexB == b.length - 1 && a[indexA] != b[indexB])
return false;
else if (indexB < b.length - 1 && a[indexA] != b[indexB])
isPermutation(a, b, indexA, indexB + 1);
}
// DEAFAULT to eliminate the error
return false;
}
尽管它应该返回 true,但它返回 false。 当我在调试器中运行时,它向我展示了递归成功地深入,但是当它退出时,它会运行返回 false 的最后一行。 我试图做布尔变量并返回它,但这给了我一个运行错误。
有什么办法可以避免写最后一行或者有其他办法解决这个问题吗?
【问题讨论】:
-
递归调用时应该返回
isPermutation的结果,否则你调用它干什么? -
@FedericoklezCulloca 我愿意,我的 if 语句没有提供任何其他选择,只能返回 true 或 false。
-
你没有。至少在所有情况下都不是。这就是您必须在末尾添加
return false的原因。我的意思是,所有对isPermutation(........);的调用都应该是return isPermutation(.......);,否则你只是忽略了递归调用返回的任何内容,然后你就会遇到return false。 -
例如假设
a.length < b.length和a[indexA] == b[indexB](即第一个else if)。在那种情况下你要返回什么?