例如:计算 C( n , k ) ,
代码如下:
function y = Binomial( n , k )
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
c = [ ] ;
for i = 1 : n
for j = 1 : i
if ( ( j == 1) || ( j == i ) )
c( i , j ) = 1 ;
else c( i , j ) = c( i -1 , j -1 ) + c( i -1 , j ) ;
end
end
end
y= c( n , k );
end
==============================
输出结果:
>> Binomial( 7 , 3)
ans =
1 0 0 0 0 0 0
1 1 0 0 0 0 0
1 2 1 0 0 0 0
1 3 3 1 0 0 0
1 4 6 4 1 0 0
1 5 10 10 5 1 0
1 6 15 20 15 6 1
原为代码:第二个for 中 j 从0到 min( i , k )
1. 动态规划 备忘录法
备忘录方法采用自顶向下方式,为每个解过的子问题建立了备忘录以备需要时查看,避免了相同子问题的重复求解。
说明: 在非边界条件下,每次求解子问题时,先查找备忘录.
若子问题已经求解过了,直接取出子问题的解;若未求解过,则求解并保存到备忘录中.
此处的备忘录就是一个存储数据的容器.
Java代码
/*
@author: jarg
@TODO 动态规划 – 备忘录法 求解二项式系数
*/
/* 求解二项式系数 */
publicstaticintBinomial(intn,intm)
{
/* 边界条件 */
if(n==m || m==0)
{
return1;
}
intdate = readDate(n,m);
if(date>0)
{
/*
子问题已经计算过
读取保存在备忘录中的数据
*/
returndate;
}
else
{
/*
子问题未计算过
解出子问题,将数据保存在备忘录中
*/
intresult = Binomial(n-1,m) + Binomial(n-1,m-1);
writeDate(n,m,result);
returnresult;
}
}
/* 从备忘录中读取数据 */
publicstaticintreadDate(intn,intm)
{
for(inti=0;i
{
Map date =newHashMap();
date = demo.get(i);
if(date.get(“”+ n + m) !=null)
{
returndate.get(“”+ n + m);
}
}
return0;
}
/* 向备忘录中写入数据 */
publicstaticvoidwriteDate(intn,intm,intvalue)
{
Map date =newHashMap();
date.put(“”+ n + m,value);
demo.add(date);
}/*
@author: jarg
@TODO 动态规划 - 备忘录法 求解二项式系数
*/
/* 求解二项式系数 */
public static int Binomial(int n,int m)
{
/* 边界条件 */
if(n==m || m==0)
{
return 1;
}
int date = readDate(n,m);
if(date>0)
{
/*
子问题已经计算过
读取保存在备忘录中的数据
*/
return date;
}
else
{
/*
子问题未计算过
解出子问题,将数据保存在备忘录中
*/
int result = Binomial(n-1,m) + Binomial(n-1,m-1);
writeDate(n,m,result);
return result;
}
}
/* 从备忘录中读取数据 */
public static int readDate(int n,int m)
{
for(int i=0;i
{
Map date = new HashMap();
date = demo.get(i);
if(date.get("" + n + m) != null)
{
return date.get("" + n + m);
}
}
return 0;
}
/* 向备忘录中写入数据 */
public static void writeDate(int n,int m,int value)
{
Map date = new HashMap();
date.put("" + n + m,value);
demo.add(date);
}
2. 动态规划 迭代法:
迭代法采用自底向上方式,保存已求解的子问题,需要时取出,消除对某些子问题的重复求解.
Pascal三角形:
说明: 在非边界的情况下,二项式系数=上一行同列数值+上一行同列前一个数值.
为了节省空间,根据n的大小,定义长度为n+1的整型数组,用以存储子问题的解.
从后往前计算图中二项式系数的解,完成后,将问题解存储在数组中对应的列标号位置.
Java代码
/*
@author: jarg
@TODO: 动态规划 – 求解二项式系数
*/
/* 求二项式系数 */
publicstaticintbinomial(intn,intm)
{
intvalue[] =newint[n+1];
for(inti=0;i<=n;i++)
{
value[i] =1;
/* 边界条件m=0,n=m的情况 */
for(intj=i-1;j>0;j–)
{
value[j] = value[j] + value[j-1];
}
}
returnvalue[m];
}