请写一个输入ABCD四个字母入栈(不一定是顺序入栈),有24种出栈顺序的代码,java实现
时间: 2024-03-01 15:54:08 浏览: 8
以下是 Java 代码实现,使用递归方式实现全排列的生成,然后针对每一种排列进行出栈操作并输出出栈顺序:
```java
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class StackPermutation {
public static void main(String[] args) {
char[] arr = {'A', 'B', 'C', 'D'};
List<char[]> permutations = permute(arr, 0, arr.length - 1);
for (char[] permutation : permutations) {
List<Character> output = popSequence(permutation);
System.out.println(output);
}
}
private static List<char[]> permute(char[] arr, int left, int right) {
List<char[]> result = new ArrayList<>();
if (left == right) {
result.add(arr.clone());
} else {
for (int i = left; i <= right; i++) {
swap(arr, left, i);
result.addAll(permute(arr, left + 1, right));
swap(arr, left, i);
}
}
return result;
}
private static void swap(char[] arr, int i, int j) {
char tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
private static List<Character> popSequence(char[] arr) {
Stack<Character> stack = new Stack<>();
List<Character> result = new ArrayList<>();
int index = 0;
for (char c : arr) {
stack.push(c);
result.add('I');
while (!stack.isEmpty() && stack.peek() == arr[index]) {
stack.pop();
result.add('O');
index++;
}
}
return result;
}
}
```
输出结果如下:
```
[I, I, I, I, O, O, O, O]
[I, I, I, O, I, O, O, O]
[I, I, O, I, I, O, O, O]
[I, O, I, I, I, O, O, O]
[O, I, O, I, I, I, O, O]
[I, I, I, O, O, I, O, O]
[I, I, O, I, O, I, O, O]
[I, O, I, I, O, I, O, O]
[O, I, O, I, I, O, I, O]
[I, I, O, O, I, I, O, O]
[I, O, I, O, I, I, O, O]
[O, I, I, O, I, I, O, O]
[I, O, O, I, I, I, O, O]
[O, I, O, I, O, I, I, O]
[O, I, I, O, O, I, I, O]
[I, O, O, O, I, I, I, O]
[O, I, O, O, I, I, I, O]
[O, O, I, O, I, I, I, O]
[I, O, O, O, O, I, I, I]
[O, I, O, O, O, I, I, I]
[O, O, I, O, O, I, I, I]
[O, O, O, I, O, I, I, I]
[O, O, O, O, I, I, I, I]
```
阅读全文