杨辉三角是计算二项式乘方展开式的系数时必不可少的工具、是由数字排列而成的三角形数表。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>