==========================================================================================================================================================================
`
public static void main(String[] args) {
ways(3,2,8,2);
}
public static int ways(int M,int K,int N,int P){
int[][] dp = new int[N+1][K+1];
for (int i = 0; i <=N; i++) {
for (int j = 0; j <=K; j++) {
dp[i][j]=-1;
}
}
System.out.println(how_to_walk(M,K,N,P,dp));
return how_to_walk(M,K,N,P,dp);
}
// 由于可变参数为 index和rest ,故可将此变为二维数组
private static int how_to_walk(int index,int rest,int N,int P,int[][] dp){
//有缓存,直接取出
if (dp[index][rest]!=-1) return dp[index][rest];
//base case
if (rest==0){
if (index==P)
dp[index][rest] = 1;
return dp[index][rest];
}
if (index==1) {
dp[index][rest]=how_to_walk(2,rest-1,N,P,dp);
return dp[index][rest];
}
if (index==N) {
dp[index][rest]=how_to_walk(N-1,rest-1,N,P,dp);
return dp[index][rest];
}
dp[index][rest]= how_to_walk(index-1,rest-1,N,P,dp)+how_to_walk(index+1,rest-1,N,P,dp);
return dp[index][rest];
}
`