[英]Generate all permutations of digits of length N
I'm trying to make a pattern wherein N numbers 0-9 are displayed in every possible order.我正在尝试制作一个模式,其中 N 个数字 0-9 以各种可能的顺序显示。
class Main {
public static void perms(int[] arr, int i) {
if (i == arr.length) {
for (int j=0; j<arr.length; j++)
System.out.print(arr[j] + " ");
System.out.println();
return;
}
for (int j=i; j<arr.length; j++) {
for (int k=0; k<=9; k++) {
arr[j] = k;
perms(arr, j+1);
}
}
}
public static void main(String[] args) {
perms(new int[]{0,0}, 0);
}
}
This is the output I'm seeking for an array of length 2:这是我正在寻找长度为 2 的数组的输出:
0 0
0 1
0 2
0 3
0 4
0 5
0 6
0 7
0 8
0 9
1 0
1 1
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9
2 0
2 1
2 2
2 3
2 4
2 5
2 6
2 7
2 8
2 9
3 0
3 1
3 2
3 3
3 4
3 5
3 6
3 7
3 8
3 9
4 0
4 1
4 2
4 3
4 4
4 5
4 6
4 7
4 8
4 9
5 0
5 1
5 2
5 3
5 4
5 5
5 6
5 7
5 8
5 9
6 0
6 1
6 2
6 3
6 4
6 5
6 6
6 7
6 8
6 9
7 0
7 1
7 2
7 3
7 4
7 5
7 6
7 7
7 8
7 9
8 0
8 1
8 2
8 3
8 4
8 5
8 6
8 7
8 8
8 9
9 0
9 1
9 2
9 3
9 4
9 5
9 6
9 7
9 8
9 9
It works but there is an extra output of:它有效,但有一个额外的输出:
9 0
9 1
9 2
9 3
9 4
9 5
9 6
9 7
9 8
9 9
at the very end when I run it.在我运行它的最后。 Why is this happening and how do I get rid of it?为什么会发生这种情况,我该如何摆脱它?
My recommendation for recursive function is you should always draw a diagram to simulate your coding process.我对递归函数的建议是你应该总是画一个图表来模拟你的编码过程。 For you program:为您计划:
Then you can simply notice that, in level 1
when in loop k > 9
you have already printed all numbers you need, while the program does not stop, instead out loop j
will become to 1
and begin the next loop.然后您可以简单地注意到,在level 1
当in loop k > 9
您已经打印了所有您需要的数字,而程序不会停止,而是out loop j
将变为1
并开始下一个循环。 This is the reason while you have extra {9, 0~9}
.这就是您有额外{9, 0~9}
。
To understand why this happens, in this loop(refer to level 1), when j == 1
, variable arr = {9, 9}
(from the last loop operation when out loop j == 0
).要理解为什么会发生这种情况,在这个循环中(参考级别 1),当j == 1
,变量arr = {9, 9}
(来自最后一个循环操作,当out loop j == 0
)。 That is to say the inner loop arr[j] = k
is modifying the second variable in the array which is arr[1]
.也就是说,内部循环arr[j] = k
正在修改数组中的第二个变量arr[1]
。 This operation is the same as level 2
.此操作与level 2
相同。
One Possible solution:一种可能的解决方案:
public class Main {
public static void perms(int[] arr, int i) {
if (i == arr.length) {
for (int j=0; j<arr.length; j++)
System.out.print(arr[j] + " ");
System.out.println();
return;
}
for (int j=i; j<arr.length; j++) {
for (int k=0; k<=9; k++) {
arr[j] = k;
perms(arr, j+1);
}
// if arr = {9, 9}, break;
// this cannot put above the inner loop, I will
// leave that for you to think why
if(arr[0] == 9 && arr[1] == 9){
return;
}
}
}
public static void main(String[] args) {
perms(new int[]{0,0}, 0);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.