给定两个整数N和K ,任务是找到包含可以使用前D个数字(0、1,…,D-1)形成的长度N的所有排列的最小字符串的大小。
例子:
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 )