查找 Mth 字典序最小的二进制字符串,没有两个相邻的 1
给定两个整数N和M ,任务是找到长度为N的第 M 个字典序最小的二进制字符串(只有字符1 和 0),其中不能有两个连续的 1。
例子:
Input: N = 2, M = 3.
Output: 10
Explanation: The only strings that can be made of size 2 are [“00”, “01”, “10”] and the 3rd string is “10”.
Input: N = 3, M = 2.
Output: 001
方法:可以根据以下方法解决问题:
Form all the N sized strings and find the Mth smallest among them.
按照下面提到的步骤来实现这个想法。
- 对于每个字符,有两种选择:
- 使字符0 。
- 如果到现在形成的字符串的最后一个字符不是1 ,那么当前字符也可以是1 。
- 要实现这一点,请使用递归。
- 由于目标是找到第M 个最小的,因此对于任何字符,首先为0调用递归函数,然后为1调用递归函数(如果可以使用 1)。
- 每次形成长度为N的字符串时,增加字符串的数量
- 如果count = M ,则该字符串是所需的按字典顺序排列的第 M小字符串。
以下是上述方法的实现:
C++
// C++ code to implement the approach
#include
using namespace std;
// Declared 2 global variable
// one is the answer string and
// the other is the count of created string
string ans = "";
int Count = 0;
// Function to find the mth string.
void findString(int idx, int n,
int m, string curr)
{
// When size of string is equal to n
if (idx == n) {
// If count of strings created
// is equal to m-1
if (Count == m - 1) {
ans = curr;
}
else {
Count += 1;
}
return;
}
// Call the function to recurse for
// currentstring + "0"
curr += "0";
findString(idx + 1, n, m, curr);
curr.pop_back();
// If the last character of curr is not 1
// then similarly recurse for "1".
if (curr[curr.length() - 1] != '1') {
curr += "1";
findString(idx + 1, n, m, curr);
curr.pop_back();
}
}
// Driver Code
int main()
{
int N = 2, M = 3;
// Function call
findString(0, N, M, "");
cout << ans << endl;
return 0;
}
输出
10
时间复杂度: O(2 N )
辅助空间: O(1)