Recursion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void print(List<int> t)
{
for (int i = 0; i < t.Count; i++)
{
Console.Write(t[i] + " ");
}
}
static void addToList(List<List<int>> list, ref List<int> temp, int[] t, int j, int cDepth, int maxDepth)
{
for (int i = j; i < t.Length; i++)
{
temp.Add(t[i]);
if (cDepth == maxDepth)
{
list.Add(temp);
temp = new List<int>(temp);
temp.RemoveAt(temp.Count - 1);
}
if (cDepth + 1 <= maxDepth)
{
addToList(list, ref temp, t, i + 1, cDepth + 1, maxDepth);
temp.RemoveAt(temp.Count - 1);
}
}
}
static void Main(string[] args)
{
List<List<int>> list = new List<List<int>>();
List<int> temp = new List<int>(10);
int[] t = { 1, 2, 3 };
for (int i = 0; i < t.Length; i++)
addToList(list, ref temp, t, 0, 0, i);
foreach (List<int> e in list)
{
print(e);
Console.WriteLine();
}
}
}
}
Output:
1 2 3 1 2 1 3 2 3 1 2 3
Nested for loop
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void print(List<int> t)
{
for (int i = 0; i < t.Count; i++)
{
Console.Write(t[i] + " ");
}
}
static void Main(string[] args)
{
int [] arr = {1,2,3};
List<List<int>> list = new List<List<int>>();
for (int i = 1; i < (1 << arr.Length); i++)
{
List<int> temp = new List<int>();
for (int j = 0; j < arr.Length; j++)
{
if ((i & (1 << j)) > 0)
{
temp.Add(arr[j]);
}
}
if (temp.Count > 0)
list.Add(temp);
}
foreach (List<int> e in list)
{
print(e);
Console.WriteLine();
}
}
}
}
Output:
1 2 1 2 3 1 3 2 3 1 2 3