主题:上楼梯算法的java实现
(java1.3.1下通过)
import java.io.*;
class upstair{
public static void main(String argc[]){
int n=Integer.parseInt(argc[0]);
int a[]=new int[n+1];
int count=0;
int i,k;
a[0]=-2;
for(i=1;i<n+1;i++)
a[i]=1;
k=n;
while(a[k]!=-1){
if(sum(a)<n) k++;
if(sum(a)==n){
for(i=1;i<=k;i++)
System.out.print(a[i]+" ");
System.out.println();
count++;
a[k]=0;
while(a[--k]==2)
a[k]=0;
}
a[k]++;
}
System.out.println(n+"级楼梯的走法:"+count);
}
static int sum(int a[]){
int sum=0;
for(int i=1;i<a.length;i++)
sum+=a[i];
return sum;
}
}
import java.io.*;
class upstair{
public static void main(String argc[]){
int n=Integer.parseInt(argc[0]);
int a[]=new int[n+1];
int count=0;
int i,k;
a[0]=-2;
for(i=1;i<n+1;i++)
a[i]=1;
k=n;
while(a[k]!=-1){
if(sum(a)<n) k++;
if(sum(a)==n){
for(i=1;i<=k;i++)
System.out.print(a[i]+" ");
System.out.println();
count++;
a[k]=0;
while(a[--k]==2)
a[k]=0;
}
a[k]++;
}
System.out.println(n+"级楼梯的走法:"+count);
}
static int sum(int a[]){
int sum=0;
for(int i=1;i<a.length;i++)
sum+=a[i];
return sum;
}
}