How to find all possible subarray of an array in c# using recursion
This article outlines how to find all possible subarray of a given array. To solve the problem recursion is used in our algorithm. If we know all the subarray of a (n-1) element of array then we can easily find out the subarray for all the n elements. Language used is c#.
Following is a c# method getSubArray that returns a List of all possible subarray of mainArray. Method is using recursion in algorithm. Paramter index should be equal to the size of mainArray.
public List> getSubArray(int[] mainArray, int index)
{
List> returnArrayList = new List
>();
List> returnOldList = new List
>();
if (index == 1)
{
List
arrayint.Add(mainArray[0]);
returnArrayList.Add(arrayint);
return returnArrayList;
}
else
{
returnOldList = getSubArray(mainArray, index - 1);
foreach (var item in returnOldList)
{
returnArrayList.Add(item);
}
foreach (var item in returnOldList)
{
List
foreach (var i in item)
{
tl.Add(i);
}
tl.Add(mainArray[index - 1]);
returnArrayList.Add(tl);
}
List
arrayNewint.Add(mainArray[index - 1]);
returnArrayList.Add(arrayNewint);
return returnArrayList;
}
}