javarecursionstackcatalan

Method that checks if the method was already executed with that input


public class CatalanNumbers {

    private int howManyVariaties;
    private int catalanNumber;
    private int catalanNumber;

    public int catalan(int a) {
       if (Method was never executed with that input) {
              howManyVariaties++;
       int catalanNumber = 0;
       for (int i= 0; i < n; i++) {
           catalanNumber += catalan(i) * catalan( n- 1 -i);
       return catalanNumber

To sum it up I only want to check how the maximum stack depth is.

Can someone help me?


Solution

  • Add a Set to your class that keeps track of what input was used and check that set inside the method

    public class CatalanNumbers {
    
        private int howManyVariaties;
        private int catalanNumber;
        private int catalanNumber;
        private Set<Integer> alreadyHandled = new HashSet<>();
    
        public int catalan(int a) {
            if (alreadyHandled.add(a)) {                  
                //rest of code
            }
        }
    //...
    }