# 一道简单的阶层面试题

142人阅读 评论(0)

privatestaticint factorial(int n){

int ret=1;

for(int i=2;i<=n;ret*=i++);

return ret;

}

publicstaticint combination1(int all,int select){

return factorial(all)/factorial(select)/factorial(all-select);

}

return factorial(all)/factorial(select)*factorial(all-select);

privatestaticint factorial(int n){

if (n<0)

thrownew InvalidParameterException();

int ret=1;

if (n==0 || n==1)

return ret;

else

for(int i=2;i<=n;ret*=i++);

return ret;

}

publicstaticint combination1(int all,int select){

if (select>all || all<=0 || select<=0)

thrownew InvalidParameterException();

if (select==all)

return 1;

return factorial(all)/factorial(select)/factorial(all-select);

}

publicstaticint combination2(int all,int select){

if (select>all || all<=0 || select<=0)

thrownew InvalidParameterException();

int ret=1;

int begin=0;

if (all==select)

return ret;

//1-begin之间的数被约分掉以简化计算

if (select<all-select)

begin=all-select+1;

else

begin=select+1;

for(int i=begin;i<=all;ret*=i++);    //计算分子

for(int i=all-begin+1;i>1;ret/=i--); //被分母除

return ret;

}

privatestatic Map<String,Integer> mapTable=new HashMap<String,Integer>();

……

publicstaticint combination3(int all,int select){

if (select>all || all<=0 || select<=0)

thrownew InvalidParameterException();

int ret=1;

int begin=0;

if (all==select){

return ret;

}

String tableKey=new String(all+","+select);

Integer tableValue=mapTable.get(tableKey);

if (tableValue!=null)

return tableValue.intValue();

if (select<all-select){

begin=all-select+1;

}

else{

begin=select+1;

}

for(int i=begin;i<=all;ret*=i++);

for(int i=all-begin+1;i>1;ret/=i--);

mapTable.put(tableKey, Integer.valueOf(ret));

return ret;

}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：1168次
• 积分：31
• 等级：
• 排名：千里之外
• 原创：1篇
• 转载：6篇
• 译文：0篇
• 评论：0条
文章分类
评论排行