using System;
using System.Collections.Generic;
namespace 所有出栈可能
{
class Program
{
public static void Myfun(string str,List<string> res)
{
string temp = "";
Produce(str, temp, res);
Distinct(res);
for (int i = 0; i < res.Count; i++)
{
Stack<char> S = new Stack<char>();
for (int j = 0,index=0; j < str.Length; j++)
{
S.Push(str[j]);
while (S.Count>0&&S.Peek() == res[i][index])
{
S.Pop();
index++;
}
}
if (S.Count > 0) res.RemoveAt(i--);
}
}
static void Distinct(List<string> res)
{
for (int i = 0; i < res.Count-1; i++)
{
for (int j = i+1; j < res.Count; j++)
{
if (res[i] == res[j])
res.RemoveAt(j--);
}
}
}
static void Produce(string str,string temp ,List<string> res)
{
if (temp.Length == str.Length)
{
res.Add(temp);
return;
}
for (int i = 0; i < str.Length; i++)
{
temp += str[i];
Produce(str, temp, res);
temp = temp.Remove(temp.Length - 1);
}
}
static void Main(string[] args)
{
string str = Console.ReadLine();
List<string> res = new List<string>();
Myfun(str, res);
foreach (var item in res)
{
Console.WriteLine(item);
}
Console.WriteLine(res.Count);
}
}
}
几点说明
- 出栈特点:当入栈为有序时,出栈的大数后面比它小的数一定是降序排列。否者不合法,
- 常规特点:当判断一个序列是否是正确是出栈顺序,先入栈一个元素,然后判断栈顶是否和出栈序列值相同,否者继续入栈,直到与之匹配。然后一直出栈,直到不匹配。再次继续之前的操作直到,入栈序列为空。
- 数列去重:值去重,对于存储对象的数列无效
using System.linq;
List<int> tt=new List<int>(){1,2,2,1};
tt=tt.Distinct().toList();
List<int> tt=new List<int>(){1,2,2,1};
tt=new HashSet<int>(tt).toList();
- 如果是对象,则利用存储对象的值转字符串或直接对象的值进行比较,然后RemoveAt()
static void Distinct(List<string> res)
{
for (int i = 0; i < res.Count-1; i++)
{
for (int j = i+1; j < res.Count; j++)
{
if (res[i] == res[j])
res.RemoveAt(j--);
}
}
}
小知识点-给编辑基础差的看
- && :逻辑与
当前面的条件判断为false时,后面的条件就不再判断。
S.Count>0&&S.Peek() == res[i][index]
这里这是因为如此才能这么写,否者:当完全匹配时,栈顶为空,res[i][index]数组越界
- j- - ;
j使用之后,数量减一。
if (res[i] == res[j])
res.RemoveAt(j--);
//if (res[i] == res[j]) res.RemoveAt(j--); 这样代码的可读性会更强