Imprimir formas de obtener la suma dada mediante lanzamientos repetidos de un dado

Dado un número entero N , la tarea es imprimir las formas de obtener la suma N lanzando repetidamente un dado.

Entrada: N = 3
Salida: 
1 1 1
1 2
2 1
3
Explicación: El dado estándar tiene 6 caras, es decir, {1, 2, 3, 4, 5, 6}. Por lo tanto, las formas de obtener la suma 3 después de lanzar repetidamente un dado son las siguientes:
1 + 1 + 1 = 3
1 + 2 = 3
2 + 1 = 3
3 = 3

Entrada: N = 2
Salida: 
1 1
2

Enfoque: este problema se puede resolver utilizando recursividad y retroceso . La idea es iterar para cada valor posible de dados i en el rango [1, 6] y recursivamente llamar a la suma restante, es decir, ( N – i ) y seguir agregando el valor del dado actual en una estructura de datos como strings . Si la suma requerida es cero, imprima los elementos en la string almacenada.

A continuación se muestra la implementación del enfoque anterior.

C++

// C++ program of the above approach
#include <iostream>
using namespace std;
 
// Recursive function to print the
// number of ways to get the sum
// N with repeated throw of a dice
void printWays(int n, string ans)
{
    // Base Case
    if (n == 0) {
 
        // Print characters in
        // the string
        for (auto x : ans) {
            cout << x << " ";
        }
        cout << endl;
        return;
    }
 
    // If n is less than zero,
    // no sum is possible
    else if (n < 0) {
        return;
    }
 
    // Loop to iterate over all
    // the possible current moves
    for (int i = 1; i <= 6; i++) {
 
        // Recursive call for the
        // remaining sum considering
        // i as the current integer
        printWays(n - i, ans + to_string(i));
    }
}
 
// Driver Code
int main()
{
    int N = 3;
    printWays(N, "");
    return 0;
}

Java

// Java program for the above approach
import java.util.*;
public class GFG {
     
// Recursive function to print the
// number of ways to get the sum
// N with repeated throw of a dice
static void printWays(int n, String ans)
{
   
    // Base Case
    if (n == 0) {
 
        // Print characters in
        // the string
        for (int i = 0; i < ans.length(); i++) {
            System.out.print(ans.charAt(i) + " ");
        }
        System.out.println();
        return;
    }
 
    // If n is less than zero,
    // no sum is possible
    else if (n < 0) {
        return;
    }
 
    // Loop to iterate over all
    // the possible current moves
    for (int i = 1; i <= 6; i++) {
 
        // Recursive call for the
        // remaining sum considering
        // i as the current integer
        printWays(n - i, ans + Integer.toString(i));
    }
}
 
// Driver Code
public static void main(String args[])
{
    int N = 3;
    printWays(N, "");
 
}
}
 
// This code is contributed by Samim Hossain Mondal.

Python3

# Python code for the above approach
 
# Recursive function to print the
# number of ways to get the sum
# N with repeated throw of a dice
def printWays(n, ans):
 
    # Base Case
    if n == 0:
 
        # Print characters in
        # the string
        for x in range(len(ans)):
            print(ans[x], end=" ")
        print("")
        return
 
    # If n is less than zero,
    # no sum is possible
    elif n < 0:
        return
 
    # Loop to iterate over all
    # the possible current moves
    for i in range(1, 7):
 
        # Recursive call for the
        # remaining sum considering
        # i as the current integer
        printWays(n - i, ans + str(i))
 
# Driver Code
N = 3
printWays(N, "")
 
# This code is contributed by gfgking

C#

// C# program for the above approach
using System;
using System.Collections;
 
class GFG {
 
  // Recursive function to print the
  // number of ways to get the sum
  // N with repeated throw of a dice
  static void printWays(int n, string ans)
  {
 
    // Base Case
    if (n == 0) {
 
      // Print characters in
      // the string
      for (int i = 0; i < ans.Length; i++) {
        Console.Write(ans[i] + " ");
      }
      Console.WriteLine();
      return;
    }
 
    // If n is less than zero,
    // no sum is possible
    else if (n < 0) {
      return;
    }
 
    // Loop to iterate over all
    // the possible current moves
    for (int i = 1; i <= 6; i++) {
 
      // Recursive call for the
      // remaining sum considering
      // i as the current integer
      printWays(n - i, ans + i.ToString());
    }
  }
 
  // Driver Code
  public static void Main()
  {
    int N = 3;
    printWays(N, "");
 
  }
}
 
// This code is contributed by Samim Hossain Mondal.

Javascript

<script>
      // JavaScript code for the above approach
 
      // Recursive function to print the
      // number of ways to get the sum
      // N with repeated throw of a dice
      function printWays(n, ans)
      {
       
          // Base Case
          if (n == 0) {
 
              // Print characters in
              // the string
              for (let x = 0; x < ans.length; x++) {
                  document.write(ans[x] + " ");
              }
              document.write('<br>')
              return;
          }
 
          // If n is less than zero,
          // no sum is possible
          else if (n < 0) {
              return;
          }
 
          // Loop to iterate over all
          // the possible current moves
          for (let i = 1; i <= 6; i++) {
 
              // Recursive call for the
              // remaining sum considering
              // i as the current integer
              printWays(n - i, ans + (i).toString());
          }
      }
 
      // Driver Code
      let N = 3;
      printWays(N, "");
 
// This code is contributed by Potta Lokesh
  </script>
Producción

1 1 1 
1 2 
2 1 
3 

Complejidad temporal: O(6 N )
Espacio auxiliar: O(1)

Publicación traducida automáticamente

Artículo escrito por prasanna1995 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *