帕斯卡的三角形格式 [英] Pascal's Triangle Format

查看:88
本文介绍了帕斯卡的三角形格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

赋值是在不使用数组的情况下创建Pascal的三角形。我有生成下面三角形值的方法。该方法接受用户想要打印的最大行数的整数。

The assignment is to create Pascal's Triangle without using arrays. I have the method that produces the values for the triangle below. The method accepts an integer for the maximum number of rows the user wants printed.

public static void triangle(int maxRows) {
    int r, num;
    for (int i = 0; i <= maxRows; i++) {
        num = 1;
        r = i + 1;
        for (int col = 0; col <= i; col++) {
            if (col > 0) {
                num = num * (r - col) / col;    
            }
            System.out.print(num + " ");
        }
        System.out.println();
    }
}

我需要格式化三角形的值,以便它看起来像一个三角形:

I need to format the values of the triangle such that it looks like a triangle:

              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

我不能为我的生活弄清楚如何做到这一点。请回答请记住,我是Java编程的初学者。

I can't for the life of me figure out how to do that. Please answer keeping in mind that I'm a beginner in Java programming.

推荐答案

public static long pascalTriangle(int r, int k)
{
    if(r == 1 || k <= 1 || k >= r) return 1L;
    return pascalTriangle(r-1, k-1) + pascalTriangle(r-1, k);
}

此方法允许您查找第r行的第k个值。

This method allows you to find the kth value of rth row.

这篇关于帕斯卡的三角形格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆