LeetCode #119 Pascal’s Triangle II Solution & Explanation

LeetCode Problem

Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal’s triangle.

In Pascal’s triangle, each number is the sum of the two numbers directly above it as shown:

Follow up: Could you optimize your algorithm to use only O(rowIndex) extra space?


Solution

In this problem, we can refer to the solution of LeetCode #118 Pascal’s Triangle. The only difference is that this problem only requires returning a specific row instead of the entire triangle.

C# Solution

Solution1

public class Solution {
    public IList<int> GetRow(int rowIndex) {
        List<int> res = new List<int>();
        
        res.Add(1);  // the first line
        
        for (int i = 1; i <= rowIndex; i++) {
            for (int j = i - 1; j >= 1; j--) {
                res[j] += res[j - 1];
            }
            res.Add(1);
        }
        
        return res;
    }
}

The loop for (int j = i – 1; j >= 1; j–) iterates from the end of the row towards the second element. This direction is chosen to prevent altering the values needed for further computations.

This way, we can use just one row for storage, without requiring any additional space.

Java Solution

Solution1

class Solution {
    public List<Integer> getRow(int rowIndex) {
        List<Integer> res = new ArrayList<Integer>();
        
        res.add(1);  // the first line
        
        for (int i = 1; i <= rowIndex; i++) {
            for (int j = i - 1; j >= 1; j--) {
                res.set(j,res.get(j) + res.get(j - 1));
            }
            res.add(1);
        }
        
        return res;
    }
}

Conclusion

🧡If my solution helps, that is my honor!

🧡You can support me by sharing my posts, thanks a lot

If you got any problem about the explanation, please feel free to let me know

The problem link : Pascal’s Triangle II – LeetCode

Similar problem :

Some Random LeetCode posts

Leave a Reply

Your email address will not be published. Required fields are marked *