What's wrong with my solusion of C++ language?


  • 0
    T
    class Solution {
    public:
        vector<vector<int>> generate(int numRows) {
                    vector<vector<int>>pT(numRows);
    				if(numRows<=0)
    			return pT;
    		int k=0;
    		for(int i=0;i<numRows;++i)
    			pT[i].resize(i+1);
    
    		pT[0][0]=1;
    
    		for(int i=1;i<numRows;++i)
    			pT[i][0]=pT[i][i]=1;
    
    		for(int i=2;i<numRows;++i)
    		{
    			for(int j=1;j<=i-1;++j)
    			{
    				pT[i][j]=pT[i-1][k]+pT[i-1][k++];
    			}
    			k=0;
    		}
    
    		return pT;
        }
    };

  • 0
    X

    Every piece of code stands for your logic thinking of programming.
    The main problem of your code is not about bad programming behavior or misunderstanding the problem but lies in how you find out the solution.

    The algorithm of pascal triangle is really simple. In your code format, it is pT[i][j] = pT[i-1][j-1]+pT[i-1][j].
    However, your way to make the triangle is way to complex and non-trial.
    Please let me pick some main fail points here:

    1. it is always good to think about bound problem. You indeed check numRows <=0. But why check it after you reference it to construct your structure? (Line 2-4)

    2. you tried to allocate the right space for the vector, which is unnecessary unless you have the space issue.

    3. you tried place these 1s first and then fill in the rest numbers, why? Would not do it baed on your original design? Use the previous row to construct the next row and you will find your code more elegant and readable.


Log in to reply
 

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