📌  相关文章
📜  打印由不超过 N 的数字字符串的字符生成的所有组合

📅  最后修改于: 2021-09-06 05:45:41             🧑  作者: Mango

给定长度为M的数字字符串S和整数N ,任务是找到S 的所有不同组合(允许重复),最多为N

例子:

方法:这个想法是使用回溯生成所有可能的数字,然后打印那些不超过N 的数字。请按照以下步骤解决问题:

  • 初始化一组字符串,比如组合[],以存储S 的所有不同组合,这些组合在数字上不超过N
  • 初始化字符串ans以存储S 中可能的当前数字组合。
  • 声明一个函数generateCombinations()以生成其值小于给定值N 的所有必需组合,该函数定义为:
    • 使用变量i[0, M]范围内遍历字符串S并执行以下操作:
      • 将当前字符S[i]推送到ans并将当前字符串ans转换为数字并存储在x 中
      • 如果x小于或等于N,则将字符串ans推入组合 []并递归调用函数generateCombinations()
    • 通过从ans 中删除第i字符来回溯到其先前的状态。
  • 完成上述步骤后,打印存储在组合[]中的所有字符串的集合。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Store the current sequence of s
string combination;
 
// Store the all the required sequences
set combinations;
 
// Function to print all sequences of S
// satisfying the required condition
void printSequences(
    set combinations)
{
    // Print all strings in the set
    for (string s : combinations) {
        cout << s << ' ';
    }
}
 
// Function to generate all sequences
// of string S that are at most N
void generateCombinations(string& s, int n)
{
 
    // Iterate over string s
    for (int i = 0; i < s.size(); i++) {
 
        // Push ith character to combination
        combination.push_back(s[i]);
 
        // Convert the string to number
        long x = stol(combination);
 
        // Check if the condition is true
        if (x <= n) {
 
            // Push the current string to
            // the final set of sequences
            combinations.insert(combination);
 
            // Recursively call function
            generateCombinations(s, n);
        }
 
        // Backtrack to its previous state
        combination.pop_back();
    }
}
 
// Driver Code
int main()
{
    string S = "124";
    int N = 100;
 
    // Function Call
    generateCombinations(S, N);
 
    // Print required sequences
    printSequences(combinations);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Store the current sequence of s
static String combination = "";
 
// Store the all the required sequences
static HashSet combinations = new LinkedHashSet();
 
// Function to print all sequences of S
// satisfying the required condition
static void printSequences(
    HashSet combinations)
{
     
    // Print all Strings in the set
    for(String s : combinations)
    {
        System.out.print(s + " ");
    }
}
 
// Function to generate all sequences
// of String S that are at most N
static void generateCombinations(String s, int n)
{
     
    // Iterate over String s
    for(int i = 0; i < s.length(); i++)
    {
         
        // Push ith character to combination
        combination += (s.charAt(i));
 
        // Convert the String to number
        long x = Integer.valueOf(combination);
 
        // Check if the condition is true
        if (x <= n)
        {
             
            // Push the current String to
            // the final set of sequences
            combinations.add(combination);
 
            // Recursively call function
            generateCombinations(s, n);
        }
 
        // Backtrack to its previous state
        combination = combination.substring(
            0, combination.length() - 1);
    }
}
 
// Driver Code
public static void main(String[] args)
{
    String S = "124";
    int N = 100;
     
    // Function Call
    generateCombinations(S, N);
 
    // Print required sequences
    printSequences(combinations);
}
}
 
// This code is contributed by Amit Katiyar


Python3
# Python3 program for the above approach
 
# Store the current sequence of s
combination = "";
 
# Store the all the required sequences
combinations = [];
 
# Function to print all sequences of S
# satisfying the required condition
def printSequences(combinations) :
     
    # Print all strings in the set
    for s in (combinations) :
        print(s, end = ' ');
  
# Function to generate all sequences
# of string S that are at most N
def generateCombinations(s, n) :   
    global combination;
 
    # Iterate over string s
    for i in range(len(s)) :
 
        # Push ith character to combination
        combination += s[i];
 
        # Convert the string to number
        x = int(combination);
 
        # Check if the condition is true
        if (x <= n) :
 
            # Push the current string to
            # the final set of sequences
            combinations.append(combination);
 
            # Recursively call function
            generateCombinations(s, n);
 
        # Backtrack to its previous state
        combination = combination[:-1];
 
# Driver Code
if __name__ == "__main__" :
 
    S = "124";
    N = 100;
 
    # Function Call
    generateCombinations(S, N);
 
    # Print required sequences
    printSequences(combinations);
 
    # This code is contributed by AnkThon


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
 
// Store the current sequence of s
static String combination = "";
 
// Store the all the required sequences
static SortedSet combinations = new SortedSet();
 
// Function to print all sequences of S
// satisfying the required condition
static void printSequences(
    SortedSet combinations)
{
     
    // Print all Strings in the set
    foreach(String s in combinations)
    {
        Console.Write(s + " ");
    }
}
 
// Function to generate all sequences
// of String S that are at most N
static void generateCombinations(String s, int n)
{
     
    // Iterate over String s
    for(int i = 0; i < s.Length; i++)
    {
         
        // Push ith character to combination
        combination += (s[i]);
 
        // Convert the String to number
        long x = Int32.Parse(combination);
 
        // Check if the condition is true
        if (x <= n)
        {
             
            // Push the current String to
            // the readonly set of sequences
            combinations.Add(combination);
 
            // Recursively call function
            generateCombinations(s, n);
        }
 
        // Backtrack to its previous state
        combination = combination.Substring(
            0, combination.Length - 1);
    }
}
 
// Driver Code
public static void Main(String[] args)
{
    String S = "124";
    int N = 100;
     
    // Function Call
    generateCombinations(S, N);
 
    // Print required sequences
    printSequences(combinations);
}
}
 
// This code is contributed by 29AjayKumar


Javascript


输出:
1 11 12 14 2 21 22 24 4 41 42 44

时间复杂度: O(N N )
辅助空间: O(N N )

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live