Segmentation Fault [Runtime Error]


I am getting segmentation fault for this trivial solution. I am not able to figure out where is the problem.

 vector<int> Solution::getRow(int A) {
    vector<vector <int>> res(A);
    vector<int> ans;
    for(int i=0; i<=A; i++)
        for(int j=0; j<=i; j++)
    for(int i=2; i<=A; i++)
        for(int j=1; j<i; j++)
            res[i][j]= res[i-1][j] + res[i-1][j-1];
    for(int i=0; i<=A; i++)        
        ans[i] = res[A][i];        
    return ans; 
    // OR
    // return res[A];

Thank you for your time and help.


In the 1st, 2nd & 3rd for-loop (in 1st and 2nd where you check the value of ‘i <= A’ & in 3rd where you ‘ans[i] = res[A][i];’), you are trying to access ‘res[A]’ position in the vector, which is out of range of the vector (since the last position int vector is ‘res[A - 1]’. Furthermore, in the 3rd loop you are trying to assign vector ‘ans’ by ‘ans[i] = res[A][i];’ which will also lead to error since ans can’t be accessed this way as it is still empty, you should use the ‘push_back()’ function like you used in the 1st loop, like ‘ans.push_back(res[A - 1][i]);’.

Also, your current method might exceed the time limit (as it is O(n^2)), try to use the other method for calculating pascal i.e. with combination formula ( nCr = n! / ((n - r)! * r!) ). It will run with faster.