I am given an input, "N", i have to find the number of list of length N, which starts with 1, such that the next number to be added is at most 1 more than the max number added till now. For Example,
N = 3, possible lists => (111, 112, 121, 122, 123), [113, or 131 is not possible as while adding '3' to the list, the maximum number present in the list would be '1', thus we can add only 1 or 2].
N = 4, the list 1213 is possible as while adding 3, the maximum number in the list is '2', thus 3 can be added.
Problem is to count the number of such lists possible for a given input "N".
My code is :-
public static void Main(string[] args) { var noOfTestCases = Convert.ToInt32(Console.ReadLine()); var listOfOutput = new List<long>(); for (int i = 0; i < noOfTestCases; i++) { var requiredSize = Convert.ToInt64(Console.ReadLine()); long result; const long listCount = 1; const long listMaxTillNow = 1; if (requiredSize < 3) result = requiredSize; else { SeqCount.Add(requiredSize, 0); AddElementToList(requiredSize, listCount, listMaxTillNow); result = SeqCount[requiredSize]; } listOfOutput.Add(result); } foreach (var i in listOfOutput) { Console.WriteLine(i); } } private static Dictionary<long, long> SeqCount = new Dictionary<long, long>(); private static void AddElementToList(long requiredSize, long listCount, long listMaxTillNow) { if (listCount == requiredSize) { SeqCount[requiredSize] = SeqCount[requiredSize] + 1; return; } var listMaxTillNowNew = listMaxTillNow + 1; for(var i = listMaxTillNowNew; i > 0; i--) { AddElementToList(requiredSize, listCount + 1, i == listMaxTillNowNew ? listMaxTillNowNew : listMaxTillNow); } return; } Which is the brute force method. I wish to know what might be the best algorithm for the problem? PS : I only wish to know the number of such lists, so i am sure creating all the list won't be required. (The way i am doing in the code) I am not at all good in algorithms, so please excuse for the long question.