Search code examples
javalistarraylistpascals-triangle

I am trying to generate list of lists to return pascals triangle


I am trying to generate pascal's triangle using powers of 11 but it works only till 4 and after 4 code needs to be modified to achieve further part of the triangle. Any leads for the answer(if possible through this method) are appreciated.

class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> a = new ArrayList<List<Integer>>();
        for (int i = 0; i < numRows; i++) {
            List<Integer> b = new ArrayList<Integer>(i);
            int c = (int) (Math.pow(11, i));
            while (c > 0) {
                int d = c % 10;
                b.add(d);
                c = c / 10;
            }
            a.add(b);
        }
        return a;
    }
}

Solution

  • Sadly, the power of 11 works up to 5th line and ends right there because of regrouping (there is a 10 so it "carries").

    Ex: Expect 11^5 = 1|5|10|10|5|1 But we get 11^5 = 161051

    You can follow different approach for printing pascal triangle.

    Optimize Way of finding pascal triangle: