1 回答
TA贡献1966条经验 获得超4个赞
我假设您不希望元素在排列中重复。例如。
如果输入阵列{1, 2, 3, 4},则对于长度3: 123,124等是有效的排列,但122还是111不是。
为了避免挑选已经挑选的元素,我们需要visited在递归中传递一个数组。
public class Main {
// Maintain a global counter. After finding a permutation, increment this.
private static int count = 0;
// pos is the current index, and K is the length of permutation you want to print, and N is the number of permutation you want to print.
private static void printPermutations(int[] arr, int[] visited, int pos, int K, int N, String str) {
// We have already found N number of permutations. We don't need anymore. So just return.
if (count == N) {
return;
}
if (pos == K) {
System.out.println(str);
count++; // we have found a valid permutation, increment counter.
return;
}
for (int i = 0; i < arr.length; i++) {
// Only recur if the ith element is not visited.
if (visited[i] == 0) {
// mark ith element as visited.
visited[i] = 1;
printPermutations(arr, visited, pos + 1, K, N, str + arr[i]);
// unmark ith element as visited.
visited[i] = 0;
}
}
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
int[] visited = {0, 0, 0, 0}; // same as size of input array.
count = 0; // make sure to reset this counter everytime you call printPermutations.
// let's print first 4 permutations of length 3.
printPermutations(arr, visited, 0, 3, 4, "");
}
}
输出:
对于 N = 4 和 K = 3(即长度为 3 的前 4 个排列):
printPermutations(arr, visited, 0, 3, 4, "");
123
124
132
134
对于 N = 4 和 K = 4(即长度为 4 的前 4 个排列):
printPermutations(arr, visited, 0, 4, 4, "");
1234
1243
1324
1342
添加回答
举报