火车进站(数组、栈、排列组合)

题目描述
给定一个正整数N代表火车数量,0 输入描述:
有多组测试用例,每一组第一行输入一个正整数N(0 输出描述:

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

思路:

先排列出所有可能,再判断是否符合

import java.util.*;

public class Main
{
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext())
        {
            int n = scanner.nextInt();
            int[] A = new int[n];
            for (int i = 0; i < n; i++)
                A[i] = scanner.nextInt();
            ArrayList result = new ArrayList<>();
            int start = 0;
            Permutation(A, start, n, result);
            Set set = new TreeSet<>();
            for (int[] out: result)
            {
                if (isLegal(A, out, n))
                {
                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < n - 1; i++)
                        sb.append(out[i] + " ");
                    sb.append(out[n - 1]);
                    set.add(sb.toString());
                }
            }
            for (String s: set)
                System.out.println(s);
        }
    }

    public static boolean isLegal(int[] in, int[] out, int n)
    {
        int i = 0;
        int j = 0;
        Stack stack = new Stack<>();
        while (i < n)
        {
            if (in[i] == out[j])
            {
                i++;
                j++;
            }
            else 
            {
                if (stack.isEmpty())
                {
                    stack.push(in[i]);
                    i++;
                }
                else 
                {
                    int top = stack.peek();
                    if (top == out[j])
                    {
                        j++;
                        stack.pop();
                    }
                    else if (i < n)
                    {
                        stack.push(in[i]);
                        i++;
                    }
                }
            }
        }
        while (!stack.isEmpty() && j < n)
        {
            int top = stack.pop();
            if (top == out[j])
                j++;
            else 
                return false;
        }
        return true;
    }

    //求出所有的排列
    public static void Permutation(int[] A, int start, int n, ArrayList result)
    {
        if (start == n)
            return;
        if (start == n - 1)
        {
            int[] B = A.clone();
            result.add(B);
            return;
        }
        for (int i = start; i < n; i++)
        {
            swap(A, i, start);
            Permutation(A, start + 1, n, result);
            swap(A, i, start);
        }
    }
    public static void swap(int[] A, int i, int j)
    {
        int tmp = A[i];
        A[i] = A[j];
        A[j] = tmp;
    }
}

你可能感兴趣的:(华为机试,数组链表,递归调用)