出栈排列


一个优化过的求所有出栈排列的函数。

        public static void GetAllStackArrangement(int[] array, int index, int[] ans,  int ansIndex, int stackIndex)
        {
            if (index >= array.Length && stackIndex >= ans.Length)
            {
                Console.WriteLine(string.Join(", ", ans));
                return;
            }
            if(stackIndex >= ans.Length)
            {
                int temp = ans[ans.Length - 1];
                ans[ans.Length - 1] = array[index++];
                GetAllStackArrangement(array, index, ans, ansIndex, ans.Length - 1);
                ans[ans.Length - 1] = temp;
            }
            else if(index >= array.Length)
            {
                int temp = ans[ansIndex], temp2 = ans[stackIndex];
                ans[ansIndex++] = ans[stackIndex++];
                GetAllStackArrangement(array, index, ans, ansIndex, stackIndex);
                ans[ansIndex - 1] = temp;
                ans[stackIndex - 1] = temp2;
            }
            else
            {
                int temp = ans[ansIndex] , temp2 = ans[stackIndex];
                ans[ansIndex++] = ans[stackIndex++];
                GetAllStackArrangement(array, index, ans, ansIndex, stackIndex);
                ansIndex--; stackIndex--;
                ans[ansIndex] = temp; ans[stackIndex] = temp2;
                temp = ans[--stackIndex];
                ans[stackIndex] = array[index++];
                GetAllStackArrangement(array, index, ans, ansIndex, stackIndex);
                ans[stackIndex] = temp;
            }
        }