I am trying to solve Dynamic Programming questions from leetcode. Started from the easiest ones. Fibonacci. I handled the IndexOutOfRangeException
and tried my code with different values on my computer. But when I submit it, leetcode says:
Runtime Error
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
At Solution.Fib(Int32 n)
At __Driver__.Main(String[] args)
Here is the code:
public class Solution
{
public int Fib(int n)
{
int[] table = new int[n 1];
// Seed the trivial answer.
table[1] = 1;
// Iterate and fill further positions based on current values.
for (int i = 0; i < n; i )
{
try
{
table[i 2] = table[i] table[i 1];
}
catch (IndexOutOfRangeException ex)
{
// Out of array bounds.
}
}
return table[n];
}
}
CodePudding user response:
Your return could be triggering that because it is outside the try/catch. Based on your logic, I don't see how you would actually get IndexOutOfRangeException there, but it could be a code quality scanner that isn't happy. Another possibility is that because your logic will always get IndexOutOfRangeException within the try/catch, the system is upset because you didn't actually 'handle' the catch, just ignored it.
CodePudding user response:
Thanks to the people at the comments, I noticed I forgot handle the cases with n<1.
public class Solution
{
public int Fib(int n)
{
if (n < 1)
{
return 0;
}
int[] table = new int[n 1];
// Seed the trivial answer.
table[1] = 1;
// Iterate and fill further positions based on current values.
for (int i = 0; i < n; i )
{
try
{
table[i 2] = table[i] table[i 1];
}
catch (IndexOutOfRangeException ex)
{
// Out of array bounds.
}
}
return table[n];
}
}
Thanks to the Klaus from the comments n - 1
instead of n
will also avoid the IndexOutOfRangeException
exception so I don't have to use try catch anymore.
for (int i = 0; i < n - 1; i ){
table[i 2] = table[i] table[i 1];
}