📌  相关文章
📜  最小数字,包含使用数字0到D的所有可能的N个长度排列

📅  最后修改于: 2021-05-05 00:23:34             🧑  作者: Mango

给定两个整数NK ,任务是找到包含可以使用前D个数字(0、1,…,D-1)形成的长度N的所有排列的最小字符串的大小。

例子:

方法:
附加“ 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 )