Java Solution | O(n) time O(n) space | 1 ms | beats 88%


  • 0
    R
    public class Solution {
    public List<Integer> getRow(int rowIndex) {
        List<Integer> res = new ArrayList<>();
        int curr[] = new int[rowIndex + 1];
        int prev[] = new int[rowIndex + 1];
        prev[0] = 1;
        
        for(int row = 1; row <= rowIndex; row++) {
            curr[0] = 1;
            curr[row] = 1;
            
            for(int i = 1; i < row; i++)
                curr[i] = prev[i] + prev[i - 1];
            
            int[] swap = curr;
            curr = prev;
            prev = swap;
        } 
        
        for(int i = 0; i <= rowIndex; i++)
            res.add(prev[i]);
            
        return res;
    }
    

    }


  • 0
    Y

    Why are you swapping the curr and prev in for loop? If I just do prev = curr, it will output [1,3,4,1] for k = 3 which I don't understand. Please explain. Thank you!


  • 0
    R

    I don't think it would since prev = curr means you are assigning the curr reference to prev. Hence in next iteration you would be working on this same array reference pointed by prev and curr which is not what we need.

    Here, we could have created a new array for each row, saying
    prev = curr;
    curr = new int[rowIndex + 1];
    but this is just wasting space and making gc to do more work than required, hence instead just swap the prev and curr references.


Log in to reply
 

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