帕斯卡三角形在一个循环中

时间:2012-04-22 13:57:37

标签: java pascals-triangle

是否可以通过使用一个循环来编写pascal的三角形?我通过使用多个循环编写它,它工作正常。

2 个答案:

答案 0 :(得分:1)

哎呀,我会把我的评论作为答案:

作为提示,我将创建一个方法,将您想要生成的三角形的行数作为输入,然后在方法的开头计算将转换为的项目的总数,然后让您的for循环遍历所有项目。在循环内部,您可以轻松计算出您所在的行以及您所在的列,然后使用此信息创建项目值。

答案 1 :(得分:0)

您想要的代码是Here

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;
    }
}

注意

此处输出符合预期

但是如果你想要格式化的视图,你需要使用额外的循环。

<强>输出

[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]