📜  没有连续相等的成对数字的N位数字的计数

📅  最后修改于: 2021-05-04 13:01:10             🧑  作者: Mango

给定一个整数N ,任务是找到N个数字的总数,以使两个连续的数字不相等。

例子:

天真的方法:解决问题的最简单方法是遍历所有可能的N位数字,并检查每个数字是否连续的两个数字相等或不相等。

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
#include
using namespace std;
 
// Function to count the number
// of N-digit numbers with no
// equal pair of consecutive digits
void count(int N)
{
     
    // Base Case
    if (N == 1)
    {
        cout << 10 << endl;
        return;
    }
 
    // Lowest N-digit number
    int l = pow(10, N - 1);
 
    // Highest N-digit number
    int r = pow(10, N) - 1;
 
    // Stores the count of all
    // required numbers
    int ans = 0;
 
    // Iterate over all N-digit numbers
    for(int i = l; i <= r; i++)
    {
        string s = to_string(i);
        int flag = 0;
 
        // Iterate over all digits
        for(int j = 1; j < N; j++)
        {
             
            // Check for equal pair of
            // adjacent digits
            if (s[j] == s[j - 1])
            {
                flag = 1;
                break;
            }
        }
        if (flag == 0)
            ans++;
    }
    cout << ans << endl;
}
 
// Driver Code
int main()
{
    int N = 2;
     
    count(N);
    return 0;
}
 
// This code is contributed by rutvik_56


Java
// Java Program to implement
// the above approach
import java.util.*;
class GFG {
 
    // Function to count the number
    // of N-digit numbers with no
    // equal pair of consecutive digits
    public static void count(int N)
    {
 
        // Base Case
        if (N == 1) {
            System.out.println(10);
            return;
        }
 
        // Lowest N-digit number
        int l = (int)Math.pow(10, N - 1);
 
        // Highest N-digit number
        int r = (int)Math.pow(10, N) - 1;
 
        // Stores the count of all
        // required numbers
        int ans = 0;
 
        // Iterate over all N-digit numbers
        for (int i = l; i <= r; i++) {
            String s = Integer.toString(i);
            int flag = 0;
 
            // Iterate over all digits
            for (int j = 1; j < N; j++) {
 
                // Check for equal pair of
                // adjacent digits
                if (s.charAt(j) == s.charAt(j - 1)) {
                    flag = 1;
                    break;
                }
            }
            if (flag == 0)
                ans++;
        }
        System.out.println(ans);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int N = 2;
        count(N);
    }
}


Python3
# Python3 Program to implement
# the above approach
 
# Function to count the number
# of N-digit numbers with no
# equal pair of consecutive digits
def count(N):
 
    # Base Case
    if (N == 1):
        print(10);
        return;
     
    # Lowest N-digit number
    l = int(pow(10, N - 1));
 
    # Highest N-digit number
    r = int(pow(10, N) - 1);
 
    # Stores the count of all
    # required numbers
    ans = 0;
 
    # Iterate over all N-digit numbers
    for i in range(l, r + 1):
        s = str(i);
        flag = 0;
 
        # Iterate over all digits
        for j in range(1, N):
 
            # Check for equal pair of
            # adjacent digits
            if (s[j] == s[j - 1]):
                flag = 1;
                break;
             
        if (flag == 0):
            ans+=1;
     
    print(ans);
 
# Driver Code
if __name__ == '__main__':
    N = 2;
    count(N);
 
# This code is contributed by sapnasingh4991


C#
// C# program to implement
// the above approach
using System;
 
class GFG{
 
// Function to count the number
// of N-digit numbers with no
// equal pair of consecutive digits
public static void count(int N)
{
     
    // Base Case
    if (N == 1)
    {
        Console.WriteLine(10);
        return;
    }
 
    // Lowest N-digit number
    int l = (int)Math.Pow(10, N - 1);
 
    // Highest N-digit number
    int r = (int)Math.Pow(10, N) - 1;
 
    // Stores the count of all
    // required numbers
    int ans = 0;
 
    // Iterate over all N-digit numbers
    for(int i = l; i <= r; i++)
    {
        String s = i.ToString();
        int flag = 0;
 
        // Iterate over all digits
        for(int j = 1; j < N; j++)
        {
 
            // Check for equal pair of
            // adjacent digits
            if (s[j] == s[j - 1])
            {
                flag = 1;
                break;
            }
        }
        if (flag == 0)
            ans++;
    }
    Console.WriteLine(ans);
}
 
// Driver Code
public static void Main(String[] args)
{
    int N = 2;
    count(N);
}
}
 
// This code is contributed by Princi Singh


C++
// C++ Program to implement
// the above approach
#include
using namespace std;
 
// Function to count the number
// of N-digit numbers with no
// equal pair of consecutive digits
void count(int N)
{
 
   // Base Case
   if (N == 1)
   {
     cout << (10) << endl;
     return;
   }
 
  int dp[N][10];
  memset(dp, 0, sizeof(dp));
  for (int i = 1; i < 10; i++)
    dp[0][i] = 1;
  for (int i = 1; i < N; i++)
  {
 
    // Calculate the total count
    // of valid (i-1)-digit numbers
    int temp = 0;
    for (int j = 0; j < 10; j++)
      temp += dp[i - 1][j];
 
    // Update dp[][] table
    for (int j = 0; j < 10; j++)
      dp[i][j] = temp - dp[i - 1][j];
  }
 
  // Calculate the count of
  // required N-digit numbers
  int ans = 0;
  for (int i = 0; i < 10; i++)
    ans += dp[N - 1][i];
  cout << ans << endl;
}
 
// Driver Code
int main()
{
  int N = 2;
  count(N);
  return 0;
}
 
// This code is contributed by sapnasingh4991


Java
// Java Program to implement
// of the above approach
import java.util.*;
class GFG {
 
    // Function to count the number
    // of N-digit numbers with no
    // equal pair of consecutive digits
    public static void count(int N)
    {
 
        // Base Case
        if (N == 1) {
            System.out.println(10);
            return;
        }
 
        int dp[][] = new int[N][10];
 
        for (int i = 1; i < 10; i++)
            dp[0][i] = 1;
        for (int i = 1; i < N; i++) {
 
            // Calculate the total count
            // of valid (i-1)-digit numbers
            int temp = 0;
            for (int j = 0; j < 10; j++)
                temp += dp[i - 1][j];
 
            // Update dp[][] table
            for (int j = 0; j < 10; j++)
                dp[i][j] = temp - dp[i - 1][j];
        }
 
        // Calculate the count of
        // required N-digit numbers
        int ans = 0;
        for (int i = 0; i < 10; i++)
            ans += dp[N - 1][i];
        System.out.println(ans);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int N = 2;
        count(N);
    }
}


Python3
# Python3 Program to implement
# of the above approach
 
# Function to count the number
# of N-digit numbers with no
# equal pair of consecutive digits
def count(N):
   
    # Base Case
    if (N == 1):
        print(10);
        return;
 
    dp = [[0 for i in range(10)]
             for j in range(N)]
 
    for i in range(1,10):
        dp[0][i] = 1;
    for i in range(1, N):
 
        # Calculate the total count
        # of valid (i-1)-digit numbers
        temp = 0;
        for j in range(10):
            temp += dp[i - 1][j];
 
        # Update dp table
        for j in range(10):
            dp[i][j] = temp - dp[i - 1][j];
 
    # Calculate the count of
    # required N-digit numbers
    ans = 0;
    for i in range(10):
        ans += dp[N - 1][i];
    print(ans);
 
# Driver Code
if __name__ == '__main__':
    N = 2;
    count(N);
 
# This code is contributed by Amit Katiyar


C#
// C# Program to implement
// of the above approach
using System;
class GFG{
 
  // Function to count the number
  // of N-digit numbers with no
  // equal pair of consecutive digits
  public static void count(int N)
  {
 
    // Base Case
    if (N == 1)
    {
      Console.WriteLine(10);
      return;
    }
 
    int [,]dp = new int[N, 10];
 
    for (int i = 1; i < 10; i++)
      dp[0, i] = 1;
    for (int i = 1; i < N; i++)
    {
 
      // Calculate the total count
      // of valid (i-1)-digit numbers
      int temp = 0;
      for (int j = 0; j < 10; j++)
        temp += dp[i - 1, j];
 
      // Update [,]dp table
      for (int j = 0; j < 10; j++)
        dp[i, j] = temp - dp[i - 1, j];
    }
 
    // Calculate the count of
    // required N-digit numbers
    int ans = 0;
    for (int i = 0; i < 10; i++)
      ans += dp[N - 1, i];
    Console.WriteLine(ans);
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    int N = 2;
    count(N);
  }
}
 
// This code is contributed by sapnasingh4991


C++
// C++ program to implement
// the above approach
#include 
using namespace std;
 
// Iterative Function to calculate
// (x^y) % mod in O(log y)
int power(int x, int y, int mod)
{
    // Initialize result
    int res = 1;
 
    // Update x if x >= mod
    x = x % mod;
 
    // If x is divisible by mod
    if (x == 0)
        return 0;
 
    while (y > 0)
    {
 
        // If y is odd, multiply x
        // with result
        if ((y & 1) == 1)
            res = (res * x) % mod;
 
        // y must be even now
        // y = y / 2
        y = y >> 1;
        x = (x * x) % mod;
    }
    return res;
}
 
// Function to count the number
// of N-digit numbers with no
// equal pair of consecutive digits
void count(int N)
{
 
    // Base Case
    if (N == 1)
    {
        cout << 10 << endl;
        return;
    }
 
    cout << (power(9, N, 1000000007)) << endl;
}
 
// Driver Code
int main()
{
    int N = 3;
    count(N);
    return 0;
}
 
// This code is contributed by sapnasingh4991


Java
// Java Program to implement
// of the above approach
import java.util.*;
 
class GFG {
 
    // Iterative Function to calculate
    // (x^y) % mod in O(log y)
    static int power(int x, int y, int mod)
    {
        // Initialize result
        int res = 1;
 
        // Update x if x >= mod
        x = x % mod;
 
        // If x is divisible by mod
        if (x == 0)
            return 0;
 
        while (y > 0) {
 
            // If y is odd, multiply x
            // with result
            if ((y & 1) == 1)
                res = (res * x) % mod;
 
            // y must be even now
            // y = y / 2
            y = y >> 1;
            x = (x * x) % mod;
        }
        return res;
    }
 
    // Function to count the number
    // of N-digit numbers with no
    // equal pair of consecutive digits
    public static void count(int N)
    {
 
        // Base Case
        if (N == 1) {
            System.out.println(10);
            return;
        }
 
        System.out.println(power(9, N,
                                 1000000007));
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int N = 3;
        count(N);
    }
}


Python3
# Python3 Program to implement
# of the above approach
 
# Iterative Function to calculate
# (x^y) % mod in O(log y)
def power(x, y, mod):
   
    # Initialize result
    res = 1;
 
    # Update x if x >= mod
    x = x % mod;
 
    # If x is divisible by mod
    if (x == 0):
        return 0;
 
    while (y > 0):
 
        # If y is odd, multiply x
        # with result
        if ((y & 1) == 1):
            res = (res * x) % mod;
 
        # y must be even now
        # y = y / 2
        y = y >> 1;
        x = (x * x) % mod;
 
    return res;
 
# Function to count the number
# of N-digit numbers with no
# equal pair of consecutive digits
def count(N):
   
    # Base Case
    if (N == 1):
        print(10);
        return;
 
    print(power(9, N, 1000000007));
 
# Driver Code
if __name__ == '__main__':
    N = 3;
    count(N);
 
# This code is contributed by Rohit_ranjan


C#
// C# program to implement
// of the above approach
using System;
 
class GFG{
 
// Iterative Function to calculate
// (x^y) % mod in O(log y)
static int power(int x, int y, int mod)
{
     
    // Initialize result
    int res = 1;
 
    // Update x if x >= mod
    x = x % mod;
 
    // If x is divisible by mod
    if (x == 0)
        return 0;
 
    while (y > 0)
    {
         
        // If y is odd, multiply x
        // with result
        if ((y & 1) == 1)
            res = (res * x) % mod;
 
        // y must be even now
        // y = y / 2
        y = y >> 1;
        x = (x * x) % mod;
    }
    return res;
}
 
// Function to count the number
// of N-digit numbers with no
// equal pair of consecutive digits
public static void count(int N)
{
 
    // Base Case
    if (N == 1)
    {
        Console.WriteLine(10);
        return;
    }
 
    Console.WriteLine(power(9, N,
                            1000000007));
}
 
// Driver Code
public static void Main(String[] args)
{
    int N = 3;
    count(N);
}
}
 
// This code is contributed by 29AjayKumar


输出:
81














时间复杂度: O(N *(10 N ),其中N是给定的整数。
辅助空间: O(1)

动态编程方法:可以使用动态编程方法对上述方法进行优化。请按照以下步骤解决问题:

  • 初始化DP [] [] ,其中DP [i] [j]存储具有i位数字并以j结尾的数字的计数。
  • 2迭代到N,然后执行以下步骤:
    • 通过将DP [i-1] [j]的所有值相加来计算有效的i-1数字总数,其中j的范围是09 ,并将其存储在temp中
    • 更新DP [i] [j] = temp – DP [i-1] [j] ,其中j的范围是0到9
  • 结果是DP [N] [j]的和,其中j的范围是0到9

下面是上述方法的实现:

C++

// C++ Program to implement
// the above approach
#include
using namespace std;
 
// Function to count the number
// of N-digit numbers with no
// equal pair of consecutive digits
void count(int N)
{
 
   // Base Case
   if (N == 1)
   {
     cout << (10) << endl;
     return;
   }
 
  int dp[N][10];
  memset(dp, 0, sizeof(dp));
  for (int i = 1; i < 10; i++)
    dp[0][i] = 1;
  for (int i = 1; i < N; i++)
  {
 
    // Calculate the total count
    // of valid (i-1)-digit numbers
    int temp = 0;
    for (int j = 0; j < 10; j++)
      temp += dp[i - 1][j];
 
    // Update dp[][] table
    for (int j = 0; j < 10; j++)
      dp[i][j] = temp - dp[i - 1][j];
  }
 
  // Calculate the count of
  // required N-digit numbers
  int ans = 0;
  for (int i = 0; i < 10; i++)
    ans += dp[N - 1][i];
  cout << ans << endl;
}
 
// Driver Code
int main()
{
  int N = 2;
  count(N);
  return 0;
}
 
// This code is contributed by sapnasingh4991

Java

// Java Program to implement
// of the above approach
import java.util.*;
class GFG {
 
    // Function to count the number
    // of N-digit numbers with no
    // equal pair of consecutive digits
    public static void count(int N)
    {
 
        // Base Case
        if (N == 1) {
            System.out.println(10);
            return;
        }
 
        int dp[][] = new int[N][10];
 
        for (int i = 1; i < 10; i++)
            dp[0][i] = 1;
        for (int i = 1; i < N; i++) {
 
            // Calculate the total count
            // of valid (i-1)-digit numbers
            int temp = 0;
            for (int j = 0; j < 10; j++)
                temp += dp[i - 1][j];
 
            // Update dp[][] table
            for (int j = 0; j < 10; j++)
                dp[i][j] = temp - dp[i - 1][j];
        }
 
        // Calculate the count of
        // required N-digit numbers
        int ans = 0;
        for (int i = 0; i < 10; i++)
            ans += dp[N - 1][i];
        System.out.println(ans);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int N = 2;
        count(N);
    }
}

Python3

# Python3 Program to implement
# of the above approach
 
# Function to count the number
# of N-digit numbers with no
# equal pair of consecutive digits
def count(N):
   
    # Base Case
    if (N == 1):
        print(10);
        return;
 
    dp = [[0 for i in range(10)]
             for j in range(N)]
 
    for i in range(1,10):
        dp[0][i] = 1;
    for i in range(1, N):
 
        # Calculate the total count
        # of valid (i-1)-digit numbers
        temp = 0;
        for j in range(10):
            temp += dp[i - 1][j];
 
        # Update dp table
        for j in range(10):
            dp[i][j] = temp - dp[i - 1][j];
 
    # Calculate the count of
    # required N-digit numbers
    ans = 0;
    for i in range(10):
        ans += dp[N - 1][i];
    print(ans);
 
# Driver Code
if __name__ == '__main__':
    N = 2;
    count(N);
 
# This code is contributed by Amit Katiyar

C#

// C# Program to implement
// of the above approach
using System;
class GFG{
 
  // Function to count the number
  // of N-digit numbers with no
  // equal pair of consecutive digits
  public static void count(int N)
  {
 
    // Base Case
    if (N == 1)
    {
      Console.WriteLine(10);
      return;
    }
 
    int [,]dp = new int[N, 10];
 
    for (int i = 1; i < 10; i++)
      dp[0, i] = 1;
    for (int i = 1; i < N; i++)
    {
 
      // Calculate the total count
      // of valid (i-1)-digit numbers
      int temp = 0;
      for (int j = 0; j < 10; j++)
        temp += dp[i - 1, j];
 
      // Update [,]dp table
      for (int j = 0; j < 10; j++)
        dp[i, j] = temp - dp[i - 1, j];
    }
 
    // Calculate the count of
    // required N-digit numbers
    int ans = 0;
    for (int i = 0; i < 10; i++)
      ans += dp[N - 1, i];
    Console.WriteLine(ans);
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    int N = 2;
    count(N);
  }
}
 
// This code is contributed by sapnasingh4991

输出:
81














时间复杂度: O(N),其中N是给定的整数
辅助空间: O(N)

高效方法:通过观察对于任何N位数字,所需的答案是9 N (可以使用二进制幂计算得出),可以进一步优化上述方法。

下面是上述方法的实现:

C++

// C++ program to implement
// the above approach
#include 
using namespace std;
 
// Iterative Function to calculate
// (x^y) % mod in O(log y)
int power(int x, int y, int mod)
{
    // Initialize result
    int res = 1;
 
    // Update x if x >= mod
    x = x % mod;
 
    // If x is divisible by mod
    if (x == 0)
        return 0;
 
    while (y > 0)
    {
 
        // If y is odd, multiply x
        // with result
        if ((y & 1) == 1)
            res = (res * x) % mod;
 
        // y must be even now
        // y = y / 2
        y = y >> 1;
        x = (x * x) % mod;
    }
    return res;
}
 
// Function to count the number
// of N-digit numbers with no
// equal pair of consecutive digits
void count(int N)
{
 
    // Base Case
    if (N == 1)
    {
        cout << 10 << endl;
        return;
    }
 
    cout << (power(9, N, 1000000007)) << endl;
}
 
// Driver Code
int main()
{
    int N = 3;
    count(N);
    return 0;
}
 
// This code is contributed by sapnasingh4991

Java

// Java Program to implement
// of the above approach
import java.util.*;
 
class GFG {
 
    // Iterative Function to calculate
    // (x^y) % mod in O(log y)
    static int power(int x, int y, int mod)
    {
        // Initialize result
        int res = 1;
 
        // Update x if x >= mod
        x = x % mod;
 
        // If x is divisible by mod
        if (x == 0)
            return 0;
 
        while (y > 0) {
 
            // If y is odd, multiply x
            // with result
            if ((y & 1) == 1)
                res = (res * x) % mod;
 
            // y must be even now
            // y = y / 2
            y = y >> 1;
            x = (x * x) % mod;
        }
        return res;
    }
 
    // Function to count the number
    // of N-digit numbers with no
    // equal pair of consecutive digits
    public static void count(int N)
    {
 
        // Base Case
        if (N == 1) {
            System.out.println(10);
            return;
        }
 
        System.out.println(power(9, N,
                                 1000000007));
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int N = 3;
        count(N);
    }
}

Python3

# Python3 Program to implement
# of the above approach
 
# Iterative Function to calculate
# (x^y) % mod in O(log y)
def power(x, y, mod):
   
    # Initialize result
    res = 1;
 
    # Update x if x >= mod
    x = x % mod;
 
    # If x is divisible by mod
    if (x == 0):
        return 0;
 
    while (y > 0):
 
        # If y is odd, multiply x
        # with result
        if ((y & 1) == 1):
            res = (res * x) % mod;
 
        # y must be even now
        # y = y / 2
        y = y >> 1;
        x = (x * x) % mod;
 
    return res;
 
# Function to count the number
# of N-digit numbers with no
# equal pair of consecutive digits
def count(N):
   
    # Base Case
    if (N == 1):
        print(10);
        return;
 
    print(power(9, N, 1000000007));
 
# Driver Code
if __name__ == '__main__':
    N = 3;
    count(N);
 
# This code is contributed by Rohit_ranjan

C#

// C# program to implement
// of the above approach
using System;
 
class GFG{
 
// Iterative Function to calculate
// (x^y) % mod in O(log y)
static int power(int x, int y, int mod)
{
     
    // Initialize result
    int res = 1;
 
    // Update x if x >= mod
    x = x % mod;
 
    // If x is divisible by mod
    if (x == 0)
        return 0;
 
    while (y > 0)
    {
         
        // If y is odd, multiply x
        // with result
        if ((y & 1) == 1)
            res = (res * x) % mod;
 
        // y must be even now
        // y = y / 2
        y = y >> 1;
        x = (x * x) % mod;
    }
    return res;
}
 
// Function to count the number
// of N-digit numbers with no
// equal pair of consecutive digits
public static void count(int N)
{
 
    // Base Case
    if (N == 1)
    {
        Console.WriteLine(10);
        return;
    }
 
    Console.WriteLine(power(9, N,
                            1000000007));
}
 
// Driver Code
public static void Main(String[] args)
{
    int N = 3;
    count(N);
}
}
 
// This code is contributed by 29AjayKumar
输出:
729














时间复杂度: O(logN)
空间复杂度: O(1)