Pascal's Triangle OJ problem


  • 1
    Z

    my code is:

    class Solution {
    public:
        vector<vector<int> > generate(int numRows) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            vector<vector<int> > res;
            if(numRows == 0)
                return res;
            res.push_back(vector<int> (1, 1));
            if(numRows == 1);
                return res;
            for(int i = 1; i < numRows; ++i) {
                vector<int> t(i + 1, 1);
                for(int j = 0; j < i - 1; ++j)
                    t[j + 1] = res[i - 1][j] + res[i - 1][j + 1];
                res.push_back(t);
            }
            return res;
        }
    };
    

    The result is:
    Input:2
    Output:[[1]]
    Expected:[[1],[1,1]]

    But it runs correctly on my own computer. You can go through this case by yourself and you will get correct result.
    Is there something wrong with OJ?
    Thank you.


  • 4

    Remove the extra semicolon at the end of your if statement.

    if(numRows == 1);     // Remove this semicolon.
        return res;

  • 0
    Z

    Thank you!!!!!!!!!!!!!!!!


  • 0

    No problem. Maybe you should start the habit of always wrapping your conditional blocks in parenthesis ({}), even the block contains only one statement. It does prevent such silly mistakes :)


  • 1
    W

    haha, this is a hidden problem, if(numRows == 1);


  • 0
    Z

    Why this habit can prevent this kind of mistakes? If you wrote "if(...);{...}" by mistake, you may alse not be able to find out the mistake.


  • 0
    S

    @zhaohaoshu, I think what 1337 mean is the habit of write if statement like if () {} always, no matter how many sentence inside the if condition. Once you get used to type if like that, you would not make such mistake. However, as you said, If you did write if(...);{...} by mistake, it is hardly to find out either.


  • 0
    N
    This post is deleted!

  • 0
    S

    Thanks for your post. However it would be better to share solution with correct code format and elaborated thoughts. Please read the Discuss FAQ for more info. Take a look at good sharing example

    Pay attention to "Writing code? Select all code then click on the {} button to preserve code formatting.” above text editor.


Log in to reply
 

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