用户应该输入他的号码中有多少位数,然后他应该输入他的号码。然后,代码应以所有可能的方式排列该数字,而不进行递归。
例如,数字123可以用6种方式排列:
123 132 213 231 312 321
请注意,如果我提出这个问题的方式有问题,或者如果需要更多信息,请告诉我。即使你不知道我的问题的答案。我真的需要回答这个问题,我想我已经开始疯狂了。
答案 0 :(得分:0)
这相当于生成所有排列。
For generating the next permutation after the current one(the first one is 123):
1. Find from right to left the first position pos where current[pos] < current[pos + 1]
2. Increment current[pos] to the next possible number(some numbers are maybe already used)
3. At the remaining positions(> pos) put the smallest possible numbers not used.
4. Go to 1.
这是一个工作代码,打印所有排列:
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Main {
public static void main(String[] args) {
final int n = 3;
int[] current = new int[n];
for (int i = 1; i <= n; i++) {
current[i - 1] = i;
}
int total = 0;
for (;;) {
total++;
boolean[] used = new boolean[n + 1];
Arrays.fill(used, true);
for (int i = 0; i < n; i++) {
System.out.print(current[i] + " ");
}
System.out.println();
used[current[n - 1]] = false;
int pos = -1;
for (int i = n - 2; i >= 0; i--) {
used[current[i]] = false;
if (current[i] < current[i + 1]) {
pos = i;
break;
}
}
if (pos == -1) {
break;
}
for (int i = current[pos] + 1; i <= n; i++) {
if (!used[i]) {
current[pos] = i;
used[i] = true;
break;
}
}
for (int i = 1; i <= n; i++) {
if (!used[i]) {
current[++pos] = i;
}
}
}
System.out.println(total);
}
}
P.S。我刚刚在几分钟内编写了代码。我并不认为代码是干净的或变量被命名为好。
答案 1 :(得分:0)
一点googling左右,你会发现一些算法,例如Johnson-Trotter Algorithm,可用5行描述:
Initialize the first permutation with <1 <2 ... <n while there exists a mobile integer find the largest mobile integer k swap k and the adjacent integer it is looking at reverse the direction of all integers larger than k