转载请注明出处:http://shuiguaiqq.iteye.com/blog/2065671
网上看到的几乎都是大同小异,而本人喜欢逻辑清晰的代码,忍不住动手写了下,代码如下:
class="java" name="code">public class YangHui { public static void main(String[] args) { int n = 9; displayYangHui(n); } public static void displayYangHui(int n) { for (int i = n - 1; i >= 0; i--) { for (int j = 0; j < i; j++) { System.out.print(" "); } showRow(getRow(n - i)); } } private static void showRow(int[] row) { for (int i = 0; i < row.length; i++) { System.out.print(row[i] + " "); } System.out.println(); } private static int[] getRow(int row) { if (row == 1) { return new int[] { 1 }; } if (row == 2) { return new int[] { 1, 1 }; } int[] result = new int[row]; for (int i = 0; i < result.length; i++) { if (i == 0 || i == result.length - 1) { result[i] = 1; } else { result[i] = getRow(row - 1)[i - 1] + getRow(row - 1)[i]; } } return result; } }
?