public class TestPossibleNumbers {
public static void main(String[] args) {
int input[] = { 1, 2, 3 };
// int input[] = {10,11,12,13};
possibleNumbers(input, 0);
}
public static void possibleNumbers(int[] x, int index) {
if (index == x.length) {
for (int i = 0; i < x.length; i++) {
System.out.print(x[i] + " ");
}
System.out.println();
}
for (int i = index; i < x.length; i++) {
int temp = x[index];
x[index] = x[i];
x[i] = temp;
possibleNumbers(x, index + 1);
temp = x[index];
x[index] = x[i];
x[i] = temp;
}
}}
谁能帮我理解for循环中的代码? 这个程序完美运行。但是,我无法弄清楚它是如何工作的
最佳答案
您正在以下位置再次递归调用该方法:
possibleNumbers(x, index + 1);
因此该方法再次运行该方法,并传递了索引+1。它检查是否
if(index == x.length)
如果语句正确,它将打印数字。
然后再次进入第二个for循环(如果if语句不正确它仍然会进入)。并再次调用循环方法。它将继续进入第二个 for 循环,但当“index”等于或大于“i.length”时,for 循环的迭代不会运行,因为您指定 for 循环仅在以下情况下运行:
i<i.length
当 2 个 for 循环不执行任何迭代时,该方法将停止重复。因此,在您的情况下,当索引等于 3 时,不会运行第二个 for 循环的迭代。
尝试逐步运行调试以更深入地了解发生了什么。
关于java - 打印给定元素数组的所有可能组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50205943/