题目
https://www.lintcode.com/problem/1827/
有一个长度为 arrLen 的数组,开始有一个指针在索引 0 处。
每一步操作中,你可以将指针向左或向右移动 1 步,或者停在原地(指针不能被移动到数组范围外)。
给你两个整数 steps 和 arrLen ,请你计算并返回:在恰好执行 steps 次操作以后,指针仍然指向索引 0,0 处的方案数。由于答案可能会很大,请返回方案数 模 1000000007 后的结果。1≤steps≤5001≤arrLen≤10 ^6样例
样例 1:输入:
3
2
输出:
4
解释:
3 步后,总共有 4 种不同的方法可以停在索引 0 处。
向右,向左,不动
不动,向右,向左
向右,不动,向左
不动,不动,不动
样例 2:输入:
2
4
输出:
2
解释:
2 步后,总共有 2 种不同的方法可以停在索引 0 处。
向右,向左
不动,不动
样例 3:输入:
4
2
输出:
8
参考代码
public class Solution {/*** @param steps: steps you can move* @param arrLen: the length of the array* @return: Number of Ways to Stay in the Same Place After Some Steps*/public int numWays(int steps, int arrLen) {//算法体系课200-201 类似
// int[][] map = new int[arrLen+1][steps+1];
// for (int[] ints : map) {
// Arrays.fill(ints,-1);
// }//return dfs(0,steps,arrLen,map);return f1(steps,arrLen);}public static int f1(int steps,int arrlen){int[][] dp = new int[arrlen+1][steps+1];dp[0][0] =1;for (int rest = 1; rest <=steps ; rest++) {for (int x = 0; x <arrlen ; x++) {int ways=pick(dp,x-1,arrlen,rest-1);ways+=pick(dp,x,arrlen,rest-1);ways+=pick(dp,x+1,arrlen,rest-1);dp[x][rest] = ways%1000000007;}}return dp[0][steps];}public static int pick(int[][] dp,int x,int arrlen,int rest){if(x<0 || x>=arrlen )return 0;return dp[x][rest];}
}