每天加点油(17)

  1. 链接:https://www.nowcoder.com/questionTerminal/97ba57c35e9f4749826dc3befaeae109?pos=13&orderByHotValue=1
    来源:牛客网

给定一个正整数N代表火车数量,0<N<10,接下来输入火车入站的序列,一共N辆火车,每辆火车以数字1-9编号,火车站只有一个方向进出,同时停靠在火车站的列车中,只有先进站的出站了,后进站的才能出站。要求以字典序排序输出火车出站的序列号。

输入描述:
有多组测试用例,每一组第一行输入一个正整数N(0<N<10),第二行包括N个正整数,范围为1到9。

输出描述:
输出以字典序从小到大排序的火车出站序列号,每个编号以空格隔开,每个输出序列换行,具体见sample。

示例1
输入
3
1 2 3
输出
1 2 3
1 3 2
2 1 3
2 3 1
3 2 1

import java.util.*;
 
public class Main {
    static ArrayList<String> l = new ArrayList<String>();    //储存结果
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
            while(scanner.hasNext()) {
                l.clear();    //静态变量,每次先清空
                int nums = scanner.nextInt();
                int[] id = new int[nums];
                Stack<Integer> stack = new Stack<Integer>();
                for(int i = 0; i < nums; i++) {
                    id[i] = scanner.nextInt();
                }
                trainOut(id, 0, stack, "", 0);
                Collections.sort(l);    //对结果集排序
                for(String str:l) {
                    System.out.println(str);
                }
            }
    }
        //i为入栈次数,n为出栈次数,str存储一趟结果
    public static void trainOut(int[] id, int i, Stack<Integer> s, String str, int n) {
        if(n == id.length) {
            l.add(str);    //如果所有火车均出栈则将当前结果保存
        }
        if(!s.empty()) {       //栈非空时出栈
            int temp = s.pop();
            trainOut(id, i, s, str + temp + " ", n + 1);
            s.push(temp);    //恢复现场
        }
        if(i < id.length) {    //若所有火车没有都入栈则入栈
            s.push(id[i]);   
            trainOut(id, i+1, s, str, n);
            s.pop();        //恢复现场
        }          
    }
}
  1. 链接:https://www.nowcoder.com/questionTerminal/564f4c26aa584921bc75623e48ca3011?f=discussion
    来源:牛客网

操作给定的二叉树,将其变换为源二叉树的镜像。

输入描述:
二叉树的镜像定义:源二叉树
8
/
6 10
/ \ /
5 7 9 11
镜像二叉树
8
/
10 6
/ \ /
11 9 7 5

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public void Mirror(TreeNode root) {
        if(root == null){
            return;
        }
        if(root.left == null && root.right == null){
            return;
        }
        TreeNode Temp = root.left;
        root.left = root.right;
        root.right = Temp;
        if(root.left != null){
            Mirror(root.left);
        }
        if(root.right != null){
            Mirror(root.right);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值