Leetcode 1007 Solution

This article provides solution to leetcode question 1007 (numbers-with-same-consecutive-differences)

https://leetcode.com/problems/numbers-with-same-consecutive-differences

Solution

class Solution:
    def numsSameConsecDiff(self, n: int, k: int) -> List[int]:
        ans = []

        def dfs(i, v):
            nonlocal k

            if i == n:
                ans.append(v)
                return

            if i == 0:
                for j in range(1, 10):
                    dfs(i + 1, j)
            else:
                for j in range(0, 10):
                    last_digit = v % 10
                    if abs(last_digit - j) == k:
                        dfs(i + 1, v * 10 + j)

        dfs(0, 0)

        return ans