题解 | #火车进站#
火车进站
https://www.nowcoder.com/practice/97ba57c35e9f4749826dc3befaeae109
import java.util.*; public class Main { public static List<List<Integer>> getAllPermutations(int[] input) { List<List<Integer>> result = new ArrayList<>(); Stack<Integer> stack = new Stack<>(); generatePermutations(input, 0, stack, new ArrayList<>(), result); return result; } private static void generatePermutations(int[] input, int index, Stack<Integer> stack, List<Integer> current, List<List<Integer>> result) { if (index == input.length && stack.isEmpty()) { // 当入栈顺序遍历完成且栈为空时,将当前出栈顺序加入结果集,注意这里是new了一个list。 result.add(new ArrayList<>(current)); return; } // 入栈 if (index < input.length) { stack.push(input[index]); generatePermutations(input, index + 1, stack, current, result); stack.pop(); } // 出栈 if (!stack.isEmpty()) { int popped = stack.pop(); current.add(popped); generatePermutations(input, index, stack, current, result); current.remove(current.size() - 1); stack.push(popped); } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int count = sc.nextInt(); int[] input = new int[count]; for(int i = 0;i < count;i++){ input[i] = sc.nextInt(); } List<List<Integer>> permutations = getAllPermutations(input); permutations.sort((o1,o2) ->{ for(int i = 0;i < o1.size();i++){ int result = o1.get(i) - o2.get(i); if(result != 0){ return result; } } return 0; }); for (List<Integer> permutation : permutations) { for(int a:permutation){ System.out.print(a+ " "); } System.out.println(); } } }
感觉写的挺规整的,记录一下。