📜  数不超过前两位绝对差的N位数字

📅  最后修改于: 2021-09-22 09:49:31             🧑  作者: Mango

给定一个整数N ,任务是计算N 位数字的数量,使得除第一位和第二位之外的每一位数字都小于或等于前两位数字的绝对差。

例子:

朴素的方法:最简单的方法是迭代所有可能的N位数字,对于每个这样的数字,检查其所有数字是否满足上述条件。

时间复杂度: O(10 N *N)
辅助空间: O(1)

高效方法:在高效方法中,构建所有可能的数字,而不是验证一系列数字的条件。这可以在动态规划的帮助下实现,因为它具有重叠的子问题和最优子结构。子问题可以利用记忆化其中DP [位] [prev1] [prev2]存储从数字个位置,直到结束时,当上一个数字选择的答案,是prev1并且被存储在DP [] [] []表选择的第二个前一位数字是prev2。

请按照以下步骤解决问题:

  • 通过执行以下步骤定义递归函数countOfNumbers(digit, prev1, prev2)
    • 检查基本情况。如果digit的值等于N+1,则在形成有效的N 位数字时返回 1
    • 如果状态结果DP [数字] [prev1] [prev2]已经计算,返回此状态DP [数字] [prev1] [prev2。
    • 如果当前数字1 ,则可以放置[1-9] 中的任何数字。如果N=1 ,则也可以放置0
    • 如果当前数字2 ,则可以放置[0-9] 中的任何数字。
    • 否则,可以将[0-(abs(prev1-prev2))] 中的任何数字放置在当前位置。
    • 进行有效放置后,递归调用countOfNumbers函数以获取索引digit+1
    • 返回所有可能的有效数字位置的总和作为答案。

下面是上述方法的代码:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
long long dp[50][10][10];
 
// Function to count N digit numbers whose
// digits are less than or equal to the
// absolute difference of previous two digits
long long countOfNumbers(int digit, int prev1,
                         int prev2, int N)
{
    // If all digits are traversed
    if (digit == N + 1)
        return 1;
 
    // If the state has already been computed
    if (dp[digit][prev1][prev2] != -1)
        return dp[digit][prev1][prev2];
 
    dp[digit][prev1][prev2] = 0;
 
    // If the current digit is 1,
    // any digit from [1-9] can be placed.
    // If N==1, 0 can also be placed.
    if (digit == 1) {
        for (int j = (N == 1 ? 0 : 1);
             j <= 9; ++j) {
 
            dp[digit][prev1][prev2]
                += countOfNumbers(digit + 1,
                                  j, prev1, N);
        }
    }
 
    // If the current digit is 2, any
    // digit from [0-9] can be placed
    else if (digit == 2) {
        for (int j = 0; j <= 9; ++j) {
 
            dp[digit][prev1][prev2]
                += countOfNumbers(
                    digit + 1, j, prev1, N);
        }
    }
 
    // For other digits, any digit
    // from 0 to abs(prev1 - prev2) can be placed
    else {
        for (int j = 0; j <= abs(prev1 - prev2); ++j) {
 
            dp[digit][prev1][prev2]
                += countOfNumbers(digit + 1, j, prev1, N);
        }
    }
 
    // Return the answer
    return dp[digit][prev1][prev2];
}
 
// Driver code
int main()
{
    // Initializing dp array with -1.
    memset(dp, -1, sizeof dp);
 
    // Input
    int N = 3;
 
    // Function call
    cout << countOfNumbers(1, 0, 0, N) << endl;
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
     
static int dp[][][] = new int[50][10][10];
 
static void initialize()
{
    for(int i = 0; i < 50; i++)
    {
        for(int j = 0; j < 10; j++)
        {
            for(int k = 0; k < 10; k++)
            {
                dp[i][j][k] = -1;
            }
        }
    }
}
  
// Function to count N digit numbers whose
// digits are less than or equal to the
// absolute difference of previous two digits
static int countOfNumbers(int digit, int prev1,
                          int prev2, int N)
{
     
    // If all digits are traversed
    if (digit == N + 1)
        return 1;
  
    // If the state has already been computed
    if (dp[digit][prev1][prev2] != -1)
        return dp[digit][prev1][prev2];
  
    dp[digit][prev1][prev2] = 0;
  
    // If the current digit is 1,
    // any digit from [1-9] can be placed.
    // If N==1, 0 can also be placed.
    if (digit == 1)
    {
        for(int j = (N == 1 ? 0 : 1);
                j <= 9; ++j)
        {
            dp[digit][prev1][prev2] += countOfNumbers(
                digit + 1, j, prev1, N);
        }
    }
  
    // If the current digit is 2, any
    // digit from [0-9] can be placed
    else if (digit == 2)
    {
        for(int j = 0; j <= 9; ++j)
        {
            dp[digit][prev1][prev2] += countOfNumbers(
                    digit + 1, j, prev1, N);
        }
    }
  
    // For other digits, any digit
    // from 0 to abs(prev1 - prev2) can be placed
    else
    {
        for(int j = 0; j <= Math.abs(prev1 - prev2); ++j)
        {
            dp[digit][prev1][prev2] += countOfNumbers(
                digit + 1, j, prev1, N);
        }
    }
  
    // Return the answer
    return dp[digit][prev1][prev2];
}
     
// Driver Code
public static void main(String[] args)
{
    initialize();
      
    // Input
    int N = 3;
  
    // Function call
    System.out.print(countOfNumbers(1, 0, 0, N));
}
}
 
// This code is contributed by susmitakundugoaldanga


Python3
# Python3 program for the above approach
dp = [[[-1 for i in range(10)]
           for j in range(10)]
           for k in range(50)]
 
# Function to count N digit numbers whose
# digits are less than or equal to the
# absolute difference of previous two digits
def countOfNumbers(digit, prev1, prev2, N):
     
    # If all digits are traversed
    if (digit == N + 1):
        return 1
 
    # If the state has already been computed
    if (dp[digit][prev1][prev2] != -1):
        return dp[digit][prev1][prev2]
 
    dp[digit][prev1][prev2] = 0
 
    # If the current digit is 1,
    # any digit from [1-9] can be placed.
    # If N==1, 0 can also be placed.
    if (digit == 1):
        term = 0 if N == 1 else 1
         
        for j in range(term, 10, 1):
            dp[digit][prev1][prev2] += countOfNumbers(
                digit + 1, j, prev1, N)
 
    # If the current digit is 2, any
    # digit from [0-9] can be placed
    elif (digit == 2):
        for j in range(10):
            dp[digit][prev1][prev2] += countOfNumbers(
                digit + 1, j, prev1, N)
 
    # For other digits, any digit
    # from 0 to abs(prev1 - prev2) can be placed
    else:
        for j in range(abs(prev1 - prev2) + 1):
            dp[digit][prev1][prev2] += countOfNumbers(
                digit + 1, j, prev1, N)
 
    # Return the answer
    return dp[digit][prev1][prev2]
 
# Driver code
if __name__ == '__main__':
     
    # Input
    N = 3
     
    # Function call
    print(countOfNumbers(1, 0, 0, N))
     
# This code is contributed by ipg2016107


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
static int [,,]dp = new int[50, 10, 10];
 
static void initialize()
{
    for(int i = 0; i < 50; i++)
    {
        for(int j = 0; j < 10; j++)
        {
            for(int k = 0; k < 10; k++)
            {
                dp[i, j, k] = -1;
            }
        }
    }
}
 
// Function to count N digit numbers whose
// digits are less than or equal to the
// absolute difference of previous two digits
static int countOfNumbers(int digit, int prev1,
                          int prev2, int N)
{
     
    // If all digits are traversed
    if (digit == N + 1)
        return 1;
 
    // If the state has already been computed
    if (dp[digit, prev1, prev2] != -1)
        return dp[digit, prev1, prev2];
 
    dp[digit, prev1, prev2] = 0;
 
    // If the current digit is 1,
    // any digit from [1-9] can be placed.
    // If N==1, 0 can also be placed.
    if (digit == 1)
    {
        for(int j = (N == 1 ? 0 : 1);
                j <= 9; ++j)
        {
            dp[digit, prev1, prev2] += countOfNumbers(
                              digit + 1, j, prev1, N);
        }
    }
 
    // If the current digit is 2, any
    // digit from [0-9] can be placed
    else if (digit == 2)
    {
        for(int j = 0; j <= 9; ++j)
        {
            dp[digit, prev1, prev2] += countOfNumbers(
                              digit + 1, j, prev1, N);
        }
    }
 
    // For other digits, any digit
    // from 0 to abs(prev1 - prev2)
    // can be placed
    else
    {
        for(int j = 0; j <= Math.Abs(prev1 - prev2); ++j)
        {
            dp[digit, prev1, prev2] += countOfNumbers(
                              digit + 1, j, prev1, N);
        }
    }
 
    // Return the answer
    return dp[digit, prev1, prev2];
}
 
// Driver code
public static void Main()
{
    initialize();
     
    // Input
    int N = 3;
 
    // Function call
    Console.Write(countOfNumbers(1, 0, 0, N));
}
}
 
// This code is contributed by SURENDRA_GANGWAR


Javascript


输出:
375

时间复杂度: O(N * 10 3 )
辅助空间: O(N * 10 2 )