Dado un número entero N , la tarea es encontrar el número de formas de obtener la suma N lanzando repetidamente un dado.
Ejemplos:
Entrada: N = 3
Salida: 4
Explicación:
Las cuatro formas posibles de obtener N son:
- 1 + 1 + 1
- 1 + 2
- 2 + 1
- 3
Entrada: N = 2
Salida: 2
Explicación:
Las dos formas posibles de obtener N son:
- 1 + 1
- 2
Enfoque recursivo : la idea es iterar para cada valor posible de dados para obtener la suma N requerida . A continuación se muestran los pasos:
- Sea findWays() la respuesta requerida para la suma N .
- Los únicos números obtenidos del lanzamiento de dados son [1, 6] , cada uno con la misma probabilidad en un solo lanzamiento de dados.
- Por lo tanto, para cada estado, recurra a los (N – i) estados anteriores (donde 1 ≤ i ≤ 6). Por lo tanto, la relación recursiva es la siguiente:
encontrarVías(N) = encontrarVías(N – 1) + encontrarVías(N – 2) + encontrarVías(N – 3) + encontrarVías(N – 4) + encontrarVías(N – 5) + encontrarVías(N – 6)
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to find the number of ways // to get the sum N with throw of dice int findWays(int N) { // Base Case if (N == 0) { return 1; } // Stores the count of total // number of ways to get sum N int cnt = 0; // Recur for all 6 states for (int i = 1; i <= 6; i++) { if (N - i >= 0) { cnt = cnt + findWays(N - i); } } // Return answer return cnt; } // Driver Code int main() { int N = 4; // Function call cout << findWays(N); return 0; }
Java
// Java program for the above approach import java.util.*; class GFG{ // Function to find the number of ways // to get the sum N with throw of dice static int findWays(int N) { // Base Case if (N == 0) { return 1; } // Stores the count of total // number of ways to get sum N int cnt = 0; // Recur for all 6 states for(int i = 1; i <= 6; i++) { if (N - i >= 0) { cnt = cnt + findWays(N - i); } } // Return answer return cnt; } // Driver Code public static void main(String[] args) { int N = 4; // Function call System.out.print(findWays(N)); } } // This code is contributed by 29AjayKumar
Python3
# Python3 program for the above approach # Function to find the number of ways # to get the sum N with throw of dice def findWays(N): # Base case if (N == 0): return 1 # Stores the count of total # number of ways to get sum N cnt = 0 # Recur for all 6 states for i in range(1, 7): if (N - i >= 0): cnt = cnt + findWays(N - i) # Return answer return cnt # Driver Code if __name__ == '__main__': N = 4 # Function call print(findWays(N)) # This code is contributed by mohit kumar 29
C#
// C# program for // the above approach using System; class GFG{ // Function to find the number of ways // to get the sum N with throw of dice static int findWays(int N) { // Base Case if (N == 0) { return 1; } // Stores the count of total // number of ways to get sum N int cnt = 0; // Recur for all 6 states for(int i = 1; i <= 6; i++) { if (N - i >= 0) { cnt = cnt + findWays(N - i); } } // Return answer return cnt; } // Driver Code public static void Main() { int N = 4; // Function call Console.Write(findWays(N)); } } // This code is contributed by sanjoy_62
Javascript
<script> // JavaScript program for the above approach // Function to find the number of ways // to get the sum N with throw of dice function findWays(N) { // Base Case if (N == 0) { return 1; } // Stores the count of total // number of ways to get sum N var cnt = 0; // Recur for all 6 states for (var i = 1; i <= 6; i++) { if (N - i >= 0) { cnt = cnt + findWays(N - i); } } // Return answer return cnt; } // Driver Code var N = 4; // Function call document.write( findWays(N)); </script>
8
Complejidad temporal: O(6 N )
Espacio auxiliar: O(1)
Enfoque de programación dinámica: el enfoque recursivo anterior debe optimizarse tratando los siguientes subproblemas superpuestos :
Subproblemas superpuestos:
árbol de recursión parcial para N = 8 :
Subestructura óptima: como para cada estado, la recurrencia ocurre para 6 estados, por lo que la definición recursiva de dp (N) es la siguiente:
dp[N] = dp[N-1] + dp[N-2] + dp[N-3] + dp[N-4] + dp[N-5] + dp[N-6]
Siga los pasos a continuación para resolver el problema:
- Inicialice una array auxiliar dp[] de tamaño N + 1 con valor inicial -1 , donde dp[i] almacena el recuento de formas de tener sum i .
- El caso base al resolver este problema es que si N es igual a 0 en cualquier estado, el resultado de tal estado es 1 .
- Si para cualquier estado dp[i] no es igual a -1 , entonces este valor como esta subestructura ya está calculado.
Enfoque de arriba hacia abajo: a continuación se muestra la implementación del enfoque de arriba hacia abajo :
C++
// C++ Program for the above approach #include <bits/stdc++.h> using namespace std; // Function to calculate the total // number of ways to have sum N int findWays(int N, int dp[]) { // Base Case if (N == 0) { return 1; } // Return already stored result if (dp[N] != -1) { return dp[N]; } int cnt = 0; // Recur for all 6 states for (int i = 1; i <= 6; i++) { if (N - i >= 0) { cnt = cnt + findWays(N - i, dp); } } // Return the result return dp[N] = cnt; } // Driver Code int main() { // Given sum N int N = 4; // Initialize the dp array int dp[N + 1]; memset(dp, -1, sizeof(dp)); // Function Call cout << findWays(N, dp); return 0; }
Java
// Java Program for // the above approach import java.util.*; class GFG{ // Function to calculate the total // number of ways to have sum N static int findWays(int N, int dp[]) { // Base Case if (N == 0) { return 1; } // Return already // stored result if (dp[N] != -1) { return dp[N]; } int cnt = 0; // Recur for all 6 states for (int i = 1; i <= 6; i++) { if (N - i >= 0) { cnt = cnt + findWays(N - i, dp); } } // Return the result return dp[N] = cnt; } // Driver Code public static void main(String[] args) { // Given sum N int N = 4; // Initialize the dp array int []dp = new int[N + 1]; for (int i = 0; i < dp.length; i++) dp[i] = -1; // Function Call System.out.print(findWays(N, dp)); } } // This code is contributed by 29AjayKumar
Python3
# Python3 Program for the # above approach # Function to calculate # the total number of ways # to have sum N def findWays(N, dp): # Base Case if (N == 0): return 1 # Return already # stored result if (dp[N] != -1): return dp[N] cnt = 0 # Recur for all 6 states for i in range (1, 7): if (N - i >= 0): cnt = (cnt + findWays(N - i, dp)) # Return the result dp[N] = cnt return dp[N] # Driver Code if __name__ == "__main__": # Given sum N N = 4 # Initialize the dp array dp = [-1] * (N + 1) # Function Call print(findWays(N, dp)) # This code is contributed by Chitranayal
C#
// C# Program for // the above approach using System; class GFG{ // Function to calculate the total // number of ways to have sum N static int findWays(int N, int []dp) { // Base Case if (N == 0) { return 1; } // Return already stored result if (dp[N] != -1) { return dp[N]; } int cnt = 0; // Recur for all 6 states for (int i = 1; i <= 6; i++) { if (N - i >= 0) { cnt = cnt + findWays(N - i, dp); } } // Return the result return dp[N] = cnt; } // Driver Code public static void Main(String[] args) { // Given sum N int N = 4; // Initialize the dp array int []dp = new int[N + 1]; for (int i = 0; i < dp.Length; i++) dp[i] = -1; // Function Call Console.Write(findWays(N, dp)); } } // This code is contributed by Rajput-Ji
Javascript
<script> // Javascript Program for // the above approach // Function to calculate the total // number of ways to have sum N function findWays(N,dp) { // Base Case if (N == 0) { return 1; } // Return already // stored result if (dp[N] != -1) { return dp[N]; } let cnt = 0; // Recur for all 6 states for (let i = 1; i <= 6; i++) { if (N - i >= 0) { cnt = cnt + findWays(N - i, dp); } } // Return the result return dp[N] = cnt; } // Driver Code let N = 4; // Initialize the dp array let dp = new Array(N + 1); for (let i = 0; i < dp.length; i++) dp[i] = -1; // Function Call document.write(findWays(N, dp)); // This code is contributed by unknown2108 </script>
8
Complejidad temporal: O(N)
Espacio auxiliar: O(N)
Enfoque de abajo hacia arriba: a continuación se muestra la implementación del enfoque de programación dinámica de abajo hacia arriba :
C++
// C++ Program for the above approach #include <bits/stdc++.h> using namespace std; // Function to calculate the total // number of ways to have sum N void findWays(int N) { // Initialize dp array int dp[N + 1]; dp[0] = 1; // Iterate over all the possible // intermediate values to reach N for (int i = 1; i <= N; i++) { dp[i] = 0; // Calculate the sum for // all 6 faces for (int j = 1; j <= 6; j++) { if (i - j >= 0) { dp[i] = dp[i] + dp[i - j]; } } } // Print the total number of ways cout << dp[N]; } // Driver Code int main() { // Given sum N int N = 4; // Function call findWays(N); return 0; }
Java
// Java program for the above approach import java.util.*; class GFG{ // Function to calculate the total // number of ways to have sum N static void findWays(int N) { // Initialize dp array int []dp = new int[N + 1]; dp[0] = 1; // Iterate over all the possible // intermediate values to reach N for(int i = 1; i <= N; i++) { dp[i] = 0; // Calculate the sum for // all 6 faces for(int j = 1; j <= 6; j++) { if (i - j >= 0) { dp[i] = dp[i] + dp[i - j]; } } } // Print the total number of ways System.out.print(dp[N]); } // Driver Code public static void main(String[] args) { // Given sum N int N = 4; // Function call findWays(N); } } // This code is contributed by Amit Katiyar
Python3
# Python3 program for # the above approach # Function to calculate the total # number of ways to have sum N def findWays(N): # Initialize dp array dp = [0] * (N + 1); dp[0] = 1; # Iterate over all the # possible intermediate # values to reach N for i in range(1, N + 1): dp[i] = 0; # Calculate the sum for # all 6 faces for j in range(1, 7): if (i - j >= 0): dp[i] = dp[i] + dp[i - j]; # Print total number of ways print(dp[N]); # Driver Code if __name__ == '__main__': # Given sum N N = 4; # Function call findWays(N); # This code is contributed by 29AjayKumar
C#
// C# program for // the above approach using System; class GFG{ // Function to calculate the total // number of ways to have sum N static void findWays(int N) { // Initialize dp array int []dp = new int[N + 1]; dp[0] = 1; // Iterate over all the possible // intermediate values to reach N for(int i = 1; i <= N; i++) { dp[i] = 0; // Calculate the sum for // all 6 faces for(int j = 1; j <= 6; j++) { if (i - j >= 0) { dp[i] = dp[i] + dp[i - j]; } } } // Print the total number of ways Console.Write(dp[N]); } // Driver Code public static void Main(String[] args) { // Given sum N int N = 4; // Function call findWays(N); } } // This code is contributed by 29AjayKumar
Javascript
<script> // JavaScript program for the above approach // Function to calculate the total // number of ways to have sum N function findWays(N) { // Initialize dp array let dp = new Array(N + 1); dp[0] = 1; // Iterate over all the possible // intermediate values to reach N for(let i = 1; i <= N; i++) { dp[i] = 0; // Calculate the sum for // all 6 faces for(let j = 1; j <= 6; j++) { if (i - j >= 0) { dp[i] = dp[i] + dp[i - j]; } } } // Print the total number of ways document.write(dp[N]); } // Driver Code // Given sum N let N = 4; // Function call findWays(N); // This code is contributed by patel2127 </script>
8
Complejidad temporal: O(N)
Espacio auxiliar: O(N)
Publicación traducida automáticamente
Artículo escrito por ManishMasiwal y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA