码迷,mamicode.com
首页 > 其他好文 > 详细

[LintCode] 1835. Number of Ways to Stay in the Same Place After Some Steps I

时间:2020-03-09 01:38:36      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:mod   pre   not   step   turn   time   ace   HERE   bsp   

You have a pointer at index 00 in an array of size arrLenarrLen. At each step, you can move 11 position to the left, 11 position to the right in the array or stay in the same place (The pointer should not be placed outside the array at any time).

Given two integers stepssteps and arrLenarrLen, return the number of ways such that your pointer still at index 00 after exactly stepssteps steps.

Since the answer may be too large, return it modulo 10^9 + 710?9??+7.

Example

Example 1:

Input: 
3
2
Output: 4
Explanation: There are 4 differents ways to stay at index 0 after 3 steps.
Right, Left, Stay
Stay, Right, Left
Right, Stay, Left
Stay, Stay, Stay


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) {
        // write your code here
        return helper(steps, arrLen, 0);
    }
    
    private int helper(int steps, int arrLen, int curPos) {
        if (curPos < 0 || curPos >= arrLen) {
            return 0;
        }
        
        if (steps == 0) {
            if (curPos == 0) {
                return 1;
            }
            return 0;
        }
        
        int lStep = helper(steps - 1, arrLen, curPos - 1);
        int rStep = helper(steps - 1, arrLen, curPos + 1);
        int sStep = helper(steps - 1, arrLen, curPos);
        return lStep + rStep + sStep;
    }
}

 

[LintCode] 1835. Number of Ways to Stay in the Same Place After Some Steps I

标签:mod   pre   not   step   turn   time   ace   HERE   bsp   

原文地址:https://www.cnblogs.com/xuanlu/p/12445988.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!