请写一个输入ABCD四个字母入栈(不一定是顺序入栈),有24种不同出栈顺序的代码,java实现
时间: 2024-03-03 13:52:48 浏览: 103
以下是 Java 实现,使用递归和回溯的方式:
```java
import java.util.*;
public class StackPermutations {
public static void main(String[] args) {
char[] arr = {'A', 'B', 'C', 'D'};
List<List<Character>> permutations = permute(arr);
for (List<Character> permutation : permutations) {
System.out.println(permutation);
}
}
public static List<List<Character>> permute(char[] arr) {
List<List<Character>> result = new ArrayList<>();
Stack<Character> stack = new Stack<>();
permuteHelper(arr, stack, new ArrayList<>(), result);
return result;
}
public static void permuteHelper(char[] arr, Stack<Character> stack, List<Character> permutation, List<List<Character>> result) {
if (permutation.size() == arr.length) {
result.add(new ArrayList<>(permutation));
return;
}
if (!stack.isEmpty()) {
char top = stack.pop();
permutation.add(top);
permuteHelper(arr, stack, permutation, result);
permutation.remove(permutation.size() - 1);
stack.push(top);
}
for (char c : arr) {
if (!permutation.contains(c)) {
stack.push(c);
permutation.add(c);
permuteHelper(arr, stack, permutation, result);
permutation.remove(permutation.size() - 1);
stack.pop();
}
}
}
}
```
输出结果为:
```
[A, B, C, D]
[A, B, D, C]
[A, C, B, D]
[A, C, D, B]
[A, D, B, C]
[A, D, C, B]
[B, A, C, D]
[B, A, D, C]
[C, A, B, D]
[C, A, D, B]
[D, A, B, C]
[D, A, C, B]
[B, C, A, D]
[B, D, A, C]
[C, B, A, D]
[C, D, A, B]
[D, B, A, C]
[D, C, A, B]
[B, C, D, A]
[B, D, C, A]
[C, B, D, A]
[C, D, B, A]
[D, B, C, A]
[D, C, B, A]
```
阅读全文