Подсчитайте способы формирования строк размера N не более чем с двумя соседними разными парами.

Опубликовано: 23 Февраля, 2023

При заданном значении N задача состоит в том, чтобы найти, сколько способов можно составить двоичную строку размера N так, чтобы не более двух соседних пар имели разные значения.

Примеры:

Input: N = 1
Output: 2
Explanation: Possible ways to form string are “1”, “0”. So the answer is 2 

Input: N = 2
Output: 4
Explanation: Possible ways are “10”, “01”, “11”, “00”. So the answer is 4.

Input: N = 4
Output: 14
Explanation: Possible ways are “1111”, “1110”, “1101”, “1011”, “0111”, “1100”, “1001”, “0110”, “0011”, “1000”, “0100”, “0010”, “0001”, “0000”. So the answer is 14.

Подход: Эту проблему можно решить, следуя следующей идее:

Consider all possible cases and add them up. Since maximum, we can have 2 adjacent pairs of different values, we count the number of ways for all 3 cases individually. The 3 ways possible are as follows:

  1. No adjacent pair with different values: We can have all the same bits i.e all bits are 0 or 1. So can form 2 strings in this case.
  2. Only one adjacent pair of different values: In this case, we will have all 1s together and 0s together so that only one pair of adjacent values is different. If the 1 is the first bit then the other are 0s. The total number of ways to do so is N-1(as there can be one ‘1’ + (N-1) ‘0’, 2 ‘1’ + (N-2) ‘0’, . . ., (N-1) ‘1’ + one ‘0’). Similarly, there can be 0s first and then 1s. So (N-1) more ways. Therefore total ways in this case, is 2*(N-1).
  3. Two adjacent pairs with different values: In this case, we keep bits in two patterns to make exactly two such positions where adjacents are different:
    • Set of 1s then set of 0s and then again set of 1s – In this case, the set of 0s can be starting from the 2nd position and end maximum at the (N-1)th position (because at least first and last bit should be 1 for two adjacent different bits). So the number of ways, in this case, can be counted as the sum of the following:
      • Number of ways if the set of 0s from 2nd position = N-2 ways (As blue color balls can end from 2nd to the (N-1)th position if it starts from 2nd position.)
      • Number of ways if the set of 0s starts from 3rd position = N-3 ways. 
      • Similarly, till 0s start at (N-1)th position.
      • Therefore the total number of ways, in this case, is (N – 2) + (N – 3)+ . . . + 1 = (N – 2) * (N – 1)/2.
    • Set of 1s then set of 0s and then again set of 0s – This case is similar to the previous one. So the total number of ways, in this case, is also (N-1) * (N-2)/2.
    • So the total number of ways is 2*{(N-1)*(N-2)/2} = (N-1)*(N-2) ways.

And hence total ways possible are the combination of these 3 cases i.e., 2 + 2*(N-1) + (N-2)*(N-1).

Ниже приведена реализация описанного выше подхода.

Временная сложность: O(1)
Вспомогательное пространство: O(1)