Pascals triangle in one loop

2019-09-05 13:28发布

问题:

Is it possible to write the pascal's triangle by using one loop ? I have written it by using more than one loop and it is working fine.

回答1:

Heck, I'll make my comment an answer:

As a hint, I would create a method that takes as input the number of rows of the triangle you want to produce, then at the beginning of the method calculate total number of items this will translate out to, and then have your for loop loop through all the items. Inside the loop, you can easily calculate which row you're on and which column you're on, and then use this information to create your item value.



回答2:

the code you want is Here

or

package net.yogesh.test;

import java.util.ArrayList;
import java.util.List;

public class pascal3 {

    public static void main(String[] args) {

        int noOfRows = 10;
        int counter = 1;
        List<Integer> list = new ArrayList<Integer>();
        list.add(1);

        list = itMe(list, counter,noOfRows);
    }

    public static List<Integer> itMe(List<Integer> list, int counter,int noOfRows) {
        System.out.println(list);

        List<Integer> tempList = new ArrayList<Integer>();

        tempList.add(1);
        for (int i = 1; i < list.size(); i++) {
            tempList.add(list.get(i) + list.get(i-1));
        }
        tempList.add(1);

        if(counter != noOfRows)
            itMe(tempList, ++counter,noOfRows);

        return tempList;
    }
}

Note

here output is as expected

but if you want in formatted view than you need to use extra loop.

Output

[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]