Java 1ms, O(k) space, no math, simple solution with explanation


  • 3
    A
    public class Solution {
        public List<Integer> getRow(int rowIndex) {
            int[] row = new int[rowIndex + 1];
            row[0] = 1;
            for(int i=1; i<row.length; i++) {
                for(int j=i; j>=1; j--) {
                    row[j] += row[j-1];
                }
            }
            List<Integer> retval = new ArrayList<>();
            for(int i : row) {
                retval.add(i);
            }
            return retval;
        }
    }
    

    Each row is built in place, on top of the previous row, e.g. for k=3:

    1 0 0 0 // before the for loop
    1 1 0 0 // first iteration of outer loop, start inner loop at index 1: 0 + 1 = 1; done
    1 2 1 0 // 2nd iteration of outer loop, start inner loop at index 2: 0 + 1 = 1; 1 + 1 = 2; done
    1 3 3 1 // 3rd iteration of outer loop ...


Log in to reply
 

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