119. Pascal's Triangle II
Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle. Note that the row index starts from 0.  In Pascal's triangle, each number is the sum of the two numbers directly above it. Example: Input: 3 Output: [1,3,3,1] Follow up: Could you optimize your algorithm to use only O(k) extra space? // used pascal triangle 1 , wondering if they want me to optimize space class Solution { public List<Integer> getRow(int rowIndex) { return generate(rowIndex + 1).get(rowIndex); } private List<List<Integer>> generate(int numRows) { int n = numRows; int[][] res = new int[n][n]; // fill in the base case // fill in the first and the last on each row with 1 for(int i = 0; i < n; i++){ // row is I, col is 0, and I res[i][0] = 1; res[i][i] = 1; } // induction rule // current = top + top left // top has the same col, row - 1 // top left is row - 1, col - 1 // start from the third row, always start from the second col, ending at the last col - 1 // last col is I for(int r = 2; r < n; r++){ for(int c = 1; c < n - 1; c++){ res[r][c] = res[r - 1][c - 1] + res[r - 1][c]; } } List<List<Integer>> result = new ArrayList<>(); for(int i = 0; i < res.length; i++){ List<Integer> tmp = new ArrayList<>(); for(int j = 0; j < res[i].length; j++){ if(res[i][j] != 0){ tmp.add(res[i][j]); } } result.add(new ArrayList<>(tmp)); } return result; } } // o(k) space https://www.youtube.com/watch?v=E--waEyRooY class Solution { public List<Integer> getRow(int row) { List<Integer> res = new ArrayList<>(); if(row == 0){ res.add(1); return res; } if(row == 1){ res.add(1); res.add(1); return res; } // List<String> places = Arrays.asList("Buenos Aires", "Córdoba", "La Plata"); // https://stackoverflow.com/questions/1005073/initialization-of-an-arraylist-in-one-line List<Integer> prev = Arrays.asList(1, 1); for(int r = 2; r <= row; r++){ List<Integer> next = new ArrayList<>(); next.add(1); for(int i = 1; i < r; i++){ next.add(prev.get(i - 1) + prev.get(i)); } next.add(1); prev = next; } return prev; } }
posted on 2018-11-09 10:21 猪猪🐷 阅读(87) 评论(0) 收藏 举报
浙公网安备 33010602011771号