Given an integer rowIndex
, return the rowIndexth
a row of Pascal's triangle.
Example:
Input: n=3
Output: 1 3 3 1
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class PrintPascalTriangleII {public static void main(String[] args) {int n = 5;List<Integer> pascal = pascalTriangle(n);System.out.println(Arrays.asList(pascal));}private static List<Integer> pascalTriangle(int n) {List<List<Integer>> v = new ArrayList<List<Integer>>();for (int line = 0; line <= n; line++) {List<Integer> x = new ArrayList<Integer>();for (int i = 0; i <= line; i++) {if (line == i || i == 0)x.add(1);elsex.add(v.get(line - 1).get(i - 1) + v.get(line - 1).get(i));}v.add(x);}List<Integer> res = new ArrayList<Integer>();// find the nth row of the pascal trianglefor (int i = 0; i < v.get(n).size(); i++)res.add(v.get(n).get(i));return res;}}
C++
#include <bits/stdc++.h>using namespace std;//function to get the nth row of//pascal trianglevector<int> getRow(int rowIndex){vector<vector<int>> v;for(int line=0;line<=rowIndex;line++){vector<int> x;for(int i=0;i<=line;i++){if(line==i||i==0)x.push_back(1);elsex.push_back(v[line-1][i-1]+v[line-1][i]);}v.push_back(x);}vector<int> res;//find the nth row of the pascal trianglefor(int i=0;i<v[rowIndex].size();i++)res.push_back(v[rowIndex][i]);return res;}int main(){int n=3;vector<int> row=getRow(n);for(int i=0;i<row.size();i++)cout<<row[i]<<" ";return 0;}
No comments:
Post a Comment