Print the pascal triangle
Example:
Input: 5 Output: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class PrintPascalTriangle {public static void main(String[] args) {int n = 5;List<List<Integer>> pascal = pascalTriangle(n);System.out.println(Arrays.asList(pascal));}private static List<List<Integer>> pascalTriangle(int n) {// store the final resultList<List<Integer>> res = new ArrayList<List<Integer>>();for (int i = 0; i < n; i++) {List<Integer> v = new ArrayList<>();for (int j = 0; j <= i; j++) {// base case if last or firstif (j == 0 || j == i)v.add(1);// else sum of previous twoelsev.add(res.get(i - 1).get(j - 1) + res.get(i - 1).get(j));}res.add(v);}return res;}}
C++
#include <bits/stdc++.h>using namespace std;//function tom generate the pascal triangle//of given number of rowsvector<vector<int>> pascalTriangle(int numRows){//store the final resultvector<vector<int>> res;for(int i=0;i<numRows;i++){vector<int> v;for(int j=0;j<=i;j++){//base case if last or firstif(j==0||j==i)v.push_back(1);//else sum of previous twoelsev.push_back(res[i-1][j-1]+res[i-1][j]);}res.push_back(v);}return res;}int main(){int n=5;vector<vector<int>> pascal=pascalTriangle(n);cout<<"[\n";for(int i=0;i<pascal.size();i++){cout<<"[";for(int j=0;j<pascal[i].size();j++){if(j==pascal[i].size()-1)cout<<pascal[i][j];elsecout<<pascal[i][j]<<",";}cout<<"]";if(i!=pascal.size()-1)cout<<",";cout<<"\n";}cout<<"]";}
No comments:
Post a Comment