Leetcode throws runtime error


  • 0
    D

    can anyone tell me why this code throws exceptions when n==5;

    int climbStairs(int n) {
             int *stairs=new int (n);
            stairs[0]=1;
            stairs[1]=2;
            for (int i=2;i<n;++i){
                stairs[i]=stairs[i-1]+stairs[i-2];
            }
            return stairs[n-1];
            
        }

  • 2
    S

    Sometimes, runtime error might not provide the right last test case you failed.

    I read your code, you do not consider about the edge case, like n = 1 or n = 0

    UPDATE

    I catch it. int *stairs=new int (n); You did the dynamic allocation with wrong syntax, you should use [] instead of (). Here is the reference of right definition, and () is use for initialization. So in your code, you just create a int variable, not a int array.


  • 0
    D

    Thanks!! Shangrila!
    damn..this is an old habit that I developed from writing matlab programs...I really need to change it.
    thanks again.


  • 0
    H

    hi, dear, take a look at this

       int climbStairs2(int n) 
        {
        	if(0==n || 1==n || 2==n)
        		return n;
        		
            int *stairs=new int [n];
            stairs[0]=1;
            stairs[1]=2;
            for (int i=2;i<n;i++){
                stairs[i]=stairs[i-1]+stairs[i-2];
            }
            int temp=stairs[n-1];
            delete[] stairs;
            return temp;
    
        }

  • 2
    R

    leetcode OJ accept code like following, strongly recommended!

    int climbStairs(int n) {
         int stairs[n];
         ......
    }
    

    this is a much safer coding style within the lastest c++ standard.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.