1 回答

TA貢獻(xiàn)1966條經(jīng)驗 獲得超4個贊
我假設(shè)您不希望元素在排列中重復(fù)。例如。
如果輸入陣列{1, 2, 3, 4},則對于長度3: 123,124等是有效的排列,但122還是111不是。
為了避免挑選已經(jīng)挑選的元素,我們需要visited在遞歸中傳遞一個數(shù)組。
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
添加回答
舉報