返回介绍

solution / 0900-0999 / 0967.Numbers With Same Consecutive Differences / README_EN

发布于 2024-06-17 01:03:32 字数 3604 浏览 0 评论 0 收藏 0

967. Numbers With Same Consecutive Differences

中文文档

Description

Given two integers n and k, return _an array of all the integers of length _n_ where the difference between every two consecutive digits is _k. You may return the answer in any order.

Note that the integers should not have leading zeros. Integers as 02 and 043 are not allowed.

 

Example 1:

Input: n = 3, k = 7
Output: [181,292,707,818,929]
Explanation: Note that 070 is not a valid number, because it has leading zeroes.

Example 2:

Input: n = 2, k = 1
Output: [10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]

 

Constraints:

  • 2 <= n <= 9
  • 0 <= k <= 9

Solutions

Solution 1

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

    def dfs(n, k, t):
      if n == 0:
        ans.append(t)
        return
      last = t % 10
      if last + k <= 9:
        dfs(n - 1, k, t * 10 + last + k)
      if last - k >= 0 and k != 0:
        dfs(n - 1, k, t * 10 + last - k)

    for i in range(1, 10):
      dfs(n - 1, k, i)
    return ans
class Solution {
  public int[] numsSameConsecDiff(int n, int k) {
    List<Integer> res = new ArrayList<>();
    for (int i = 1; i < 10; ++i) {
      dfs(n - 1, k, i, res);
    }
    int[] ans = new int[res.size()];
    for (int i = 0; i < res.size(); ++i) {
      ans[i] = res.get(i);
    }
    return ans;
  }

  private void dfs(int n, int k, int t, List<Integer> res) {
    if (n == 0) {
      res.add(t);
      return;
    }
    int last = t % 10;
    if (last + k <= 9) {
      dfs(n - 1, k, t * 10 + last + k, res);
    }
    if (last - k >= 0 && k != 0) {
      dfs(n - 1, k, t * 10 + last - k, res);
    }
  }
}
class Solution {
public:
  vector<int> ans;

  vector<int> numsSameConsecDiff(int n, int k) {
    for (int i = 1; i < 10; ++i)
      dfs(n - 1, k, i);
    return ans;
  }

  void dfs(int n, int k, int t) {
    if (n == 0) {
      ans.push_back(t);
      return;
    }
    int last = t % 10;
    if (last + k <= 9) dfs(n - 1, k, t * 10 + last + k);
    if (last - k >= 0 && k != 0) dfs(n - 1, k, t * 10 + last - k);
  }
};
func numsSameConsecDiff(n int, k int) []int {
  var ans []int
  var dfs func(n, k, t int)
  dfs = func(n, k, t int) {
    if n == 0 {
      ans = append(ans, t)
      return
    }
    last := t % 10
    if last+k <= 9 {
      dfs(n-1, k, t*10+last+k)
    }
    if last-k >= 0 && k != 0 {
      dfs(n-1, k, t*10+last-k)
    }
  }

  for i := 1; i < 10; i++ {
    dfs(n-1, k, i)
  }
  return ans
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文