给定两个整数N和K ,任务是找到包含长度为N 的所有排列的最小字符串的大小,这些排列可以使用前D 个数字(0, 1, …, D-1) 形成。
例子:
Input: N = 2, D = 2
Output: 01100
Explanation:
Possible permutations of length 2 from digits (0, 1) are {00, 01, 10, 11}.
“01100” is one such string that contains all the permutations as a substring.
Other possible answers are “00110”, “10011”, “11001”
Input: N = 2, D = 4
Output: 03322312113020100
Explaination:
Here all possible permutations of length 2 from digits {0, 1, 2, 3} are
00 10 20 30
01 11 21 31
02 12 22 32
03 13 23 33
“03322312113020100” is a string of minimum length that contains all the above permutations.
方法:
追加 ‘0’ N-1 次并在当前状态的字符串上调用 DFS。将所有 D字符一一附加。每次追加后,检查新字符串是否被访问。如果是这样,通过将其插入 HashSet 并在答案中添加此字符来标记它已访问。在最后的 D 个字符上递归调用 DFS函数。重复这个过程,直到 D 位数字中所有可能的长度为 N 的子串都附加到字符串。打印生成的最终字符串。
下面是上述方法的实现:
Java
// Java Program to find the
// minimum length string
// consisting of all
// permutations of length N
// of D digits
import java.io.*;
import java.util.*;
import java.lang.*;
class GeeksforGeeks {
// Initialize hashset to see
// if all the possible
// permutations are present
// in the min length string
static Set visited;
// To keep min length string
static StringBuilder ans;
public static String reqString(int N,
int D)
{
// Base case
if (N == 1 && D == 1)
return "0";
visited = new HashSet<>();
ans = new StringBuilder();
StringBuilder sb = new StringBuilder();
// Append '0' n-1 times
for (int i = 0; i < N - 1; ++i) {
sb.append("0");
}
String start = sb.toString();
// Call the DFS Function
dfs(start, D);
ans.append(start);
return new String(ans);
}
// Generate the required string
public static void dfs(String curr, int D)
{
// Iterate over all the possible
// character
for (int x = 0; x < D; ++x) {
// Append to make a new string
String neighbour = curr + x;
// If the new string is not
// visited
if (!visited.contains(neighbour)) {
// Add in hashset
visited.add(neighbour);
// Call the dfs function on
// the last d characters
dfs(neighbour.substring(1), D);
ans.append(x);
}
}
}
// Driver Code
public static void main(String args[])
{
int N = 2;
int D = 2;
System.out.println(reqString(N, D));
}
}
01100
时间复杂度: O(N * D N )
辅助空间: O(N * D N )
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live