楊輝三角是計算二項式乘方展開式的係數時必不可少的工具、是由數字排列而成的三角形數表。javascript
資料:楊輝三角第n行的第1個數爲1,第二個數爲1×(n-1),第三個數爲1×(n-1)×(n-2)/2,第四個數爲1×(n-1)×(n-2)/2×(n-3)/3…依此類推。html
楊輝三角另一個重要的特性就是每一行首尾兩個數字都是一、中間的數字等於上一行相鄰兩個數字的和、即排列組合中一般所運用的: java
C(m,n) = C(m-1,n-1)+C(m-1,n)ide
根據以上性質、能夠利用函數很輕鬆地將楊輝三角運算出來、函數接受一個參數、即但願獲得楊輝三角的行數、代碼以下:函數
在這個函數中用兩個for循環進行嵌套、外層循環數爲行數、內層循環爲每行內的每一項、代碼以下:
- function Pascal(n){ //楊輝三角,N爲行數
- //
- }
- for( var i = 0 ; i < n ; i++ ){ //一共N行
- for ( var j = 0 ; j <= i ; j++ ) { //每行數字的個數即爲行號、例如第1行1個數、第2行2個數
- }
- document.write("<br/>");
- }
而在每行中每個數字均爲組合數C(m,n)、其中m爲行號(從0算起)、n爲在該行中的序號(從0算起)、即:工具
- document.write(Combination(i,j)+" "); //引號裏面的內容是兩個html空格( )字符
其中Combination(i,j)爲計算組合數的函數、這個函數採用組合數的特性C(m,n) = C(m-1,n-1)+C(m-1,n)、對於這樣的特性、最有效的辦法就是遞歸:ui
- function Combination(m,n){
- if(n == 0) return 1; //每行第一個數爲1
- else if(m == n) return 1; //最後一個數爲1
- //其他都是相加而來
- else return Combination(m-1,n-1)+Combination(m-1,n);
- }
完整代碼:spa
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <%--
- 楊輝三角
- createDate 2010-7-8
- author 古道西風
- --%>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>楊輝三角</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <script type="text/javascript">
- function Combination(m,n){
- if(n == 0) return 1; //每行第一個數爲1
- else if(m == n) return 1; //最後一個數爲1
- //其他都是相加而來
- else return Combination(m-1,n-1)+Combination(m-1,n);
- }
- function Pascal(n){ //楊輝三角,N爲行數
- for( var i = 0 ; i < n ; i++ ){ //一共N行
- for ( var j = 0 ; j <= i ; j++ ) { //每行數字的個數即爲行號、例如第1行1個數、第2行2個數
- document.write(Combination(i,j)+" ");
- }
- document.write("<br/>");
- }
- }
- </script>
- </head>
- <body>
- <!-- 直接傳入但願獲得的楊輝三角的行數 -->
- <input value="楊輝三角" type="button" onclick="Pascal(10);" />
- </body>
- </html>