题解 | #火车进站#
火车进站
https://www.nowcoder.com/practice/97ba57c35e9f4749826dc3befaeae109
这道题还是比较难的, 我最先开始想的也是递归, 广度就是入栈和出栈, 但是做的事情不一样, 所以无从下笔. 鼓捣一阵无果后查看答案发现了两点, 广度是进栈和出栈, 但是返回到原函数需要还原, 入栈元素的下标用i表示, 深度和结束条件相关, 就是所有元素出栈完了, 出栈了arr.length()次的时候返回原函数, 结束递归 import java.util.*; public class Main { public static ArrayList<String> list = new ArrayList<>(); public static StringBuilder sb = new StringBuilder(); public static void main(String[] args) { Scanner sc = new Scanner(System.in); Stack<Integer> stack = new Stack<>(); int n = sc.nextInt(); int []arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } recursion(0,0,arr,stack); Collections.sort(list); for (String i: list) { System.out.println(i); } } //1 2 3 public static void recursion( int len, int i, int []arr ,Stack<Integer> stack ) { if(len == arr.length) { list.add(sb.toString()); return; } //出栈 if( !stack.isEmpty()) { int k = stack.pop(); sb.append(k+" "); recursion(len+1,i,arr,stack); stack.push(k); sb.delete(sb.length()-2, sb.length()); //sb.deleteCharAt(sb.length()-1); } //入栈 if(i< arr.length) { stack.push(arr[i]); recursion(len,i+1,arr,stack); stack.pop(); } } }
华为机试题解 文章被收录于专栏
华为机试题解