Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

README.md

You are given two positive integers startPos and endPos. Initially, you are standing at position startPos on an infinite number line. With one step, you can move either one position to the left, or one position to the right.

Given a positive integer k, return the number of different ways to reach the position endPos starting from startPos, such that you perform exactly k steps. Since the answer may be very large, return it modulo 109 + 7.

Two ways are considered different if the order of the steps made is not exactly the same.

Note that the number line includes negative integers.

 

Example 1:

Input: startPos = 1, endPos = 2, k = 3
Output: 3
Explanation: We can reach position 2 from 1 in exactly 3 steps in three ways:
- 1 -> 2 -> 3 -> 2.
- 1 -> 2 -> 1 -> 2.
- 1 -> 0 -> 1 -> 2.
It can be proven that no other way is possible, so we return 3.

Example 2:

Input: startPos = 2, endPos = 5, k = 10
Output: 0
Explanation: It is impossible to reach position 5 from position 2 in exactly 10 steps.

 

Constraints:

  • 1 <= startPos, endPos, k <= 1000

Related Topics:
Math, Dynamic Programming, Combinatorics

Similar Questions:

Solution 1. Combination

We need at least abs(endPos - startPos) steps. k must >= steps. When k > steps, (k - steps) must be a even number.

With k available moves, we select steps + (k - steps) / 2 moves in the startPos-to-endPos direction, and (k - steps) / 2 moves in the opposite direction. Thus, the answer is $C_k^{(k-steps)/2}$

// OJ: https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps
// Author: github.com/lzl124631x
// Time: O(K * (K - abs(startPos - endPos)))
// Space: O(K - abs(startPos - endPos))
class Solution {
    int combination(int n, int k, int mod) {
        k = min(k, n - k);
        vector<int> dp(k + 1);
        dp[0] = 1;
        for (int i = 1; i <= n; ++i) {
            for (int j = min(i, k); j > 0; --j) {
                dp[j] = (dp[j] + dp[j - 1]) % mod;
            }
        }
        return dp[k];
    }
public:
    int numberOfWays(int startPos, int endPos, int k) {
        int steps = abs(endPos - startPos);
        if (k < steps || (k - steps) % 2) return 0;
        return combination(k, (k - steps) / 2, 1e9 + 7);
    }
};