C#以非递归方式实现三位排列组合,如下代码:
- //深度优先
- class Program
- {
- static void Main(string[] args)
- {
- int[] number = new int[] { 1, 3, 5, 7 };
- List data = new List();
- Stack openStack = new Stack();
- Tree root = new Tree();
- Tree parent =root;
- while (true)
- {
- if (parent.GetDeep() == 4)
- {
- parent.printf();
- }
- else
- {
- var tempSon= number.ToList();
- foreach (var item in tempSon)
- {
- Tree Node = new Tree();
- Node.NodeData = item;
- Node.Parent = parent;
- openStack.Push(Node);
- }
- }
- if (openStack.Count == 0)
- break;
- var itemData= openStack.Pop();
- parent = itemData;
- }
- System.Console.Read();
- }
- public static void printf(List data)
- {
- string d="";
- data.ForEach(p => d = d + p);
- System.Console.WriteLine(d);
- }
- }
- class Tree
- {
- public Tree Parent;
- public int NodeData;
- public List Son = new List();
- public int GetDeep()
- {
- int i=0;
- var p=this;
- while (true)
- {
- if (p == null)
- {
- return i;
- }
- else
- {
- p = p.Parent;
- i++;
- }
- }
- }
- public void printf()
- {
- string pf = "";
- var p = this;
- while (true)
- {
- if (p == null)
- {
- System.Console.WriteLine(pf);
- return;
- }
- else
- {
- if (p.NodeData != 0)
- {
- pf = p.NodeData + pf;
- }
- p = p.Parent;
- }
- }
- }
- }
- //广度优先
- class Program
- {
- static void Main(string[] args)
- {
- int[] number = new int[] { 1, 3};
- List<int> data = new List<int>();
- Stack<Tree> openStack = new Stack<Tree>();
- Queue<Tree> openQueue = new Queue<Tree>();
- Tree root = new Tree();
- Tree parent =root;
- while (true)
- {
- if (parent.GetDeep() == 4)
- {
- parent.printf();
- }
- else
- {
- var tempSon= number.ToList();
- foreach (var item in tempSon)
- {
- Tree Node = new Tree();
- Node.NodeData = item;
- Node.Parent = parent;
- // openStack.Push(Node);
- openQueue.Enqueue(Node);
- }
- }
- if (openQueue.Count == 0) //if (openStack.Count == 0)
- break;
- var itemData = openQueue.Dequeue(); //openStack.Pop();
- parent = itemData;
- }
- System.Console.Read();
- }
- public static void printf(List<int> data)
- {
- string d="";
- data.ForEach(p => d = d + p);
- System.Console.WriteLine(d);
- }
- }
- class Tree
- {
- public Tree Parent;
- public int NodeData;
- public List<Tree> Son = new List<Tree>();
- public int GetDeep()
- {
- int i=0;
- var p=this;
- while (true)
- {
- if (p == null)
- {
- return i;
- }
- else
- {
- p = p.Parent;
- i++;
- }
- }
- }
- public void printf()
- {
- string pf = "";
- var p = this;
- while (true)
- {
- if (p == null)
- {
- System.Console.WriteLine(pf);
- return;
- }
- else
- {
- if (p.NodeData != 0)
- {
- pf = p.NodeData + pf;
- }
- p = p.Parent;
- }
- }
- }
- }