Dados dos números N y K , la tarea es encontrar el recuento de todas las combinaciones válidas de, como máximo, K números que sumen N , de modo que se cumplan las siguientes condiciones:
- Solo se utilizan los números del 1 al 9.
- Cada número se utiliza como máximo una vez.
Ejemplos:
Entrada : K = 3, N = 7
Salida : 5
Explicación:
1 2 4
1 6
2 5
3 4
7Entrada : K = 3, N = 9
Salida : 8
Explicación:
1 2 6
1 3 5
1 8
2 3 4
2 7
3 6
4 5
9
Enfoque ingenuo: la idea es crear una array de números del 1 al 9 y encontrar el recuento de todas las subsecuencias de longitud como máximo K con suma N.
Complejidad de tiempo: O(10^2)
Espacio auxiliar: O(1)
Enfoque recursivo: el problema también se puede resolver usando recursividad de la siguiente manera:
- Cree una array de dígitos del 1 al 9 en arr.
- Cree una función de recursión que itere la array con el índice actual como i , la suma actual como sum , el recuento actual como c y el recuento resultante de combinaciones como ans .
- Caso base 1: si (suma == n && c <= k)
- Incrementar el conteo resultante de combinaciones y
- Devuelve la respuesta
- Caso base 2: si (i >= arr.size() || sum > n || c > k)
- Devuelve la respuesta
- Más
- Empuje el elemento de array actual en el vector temporal
- Llamar a la función recursiva
- Pop el elemento actual del vector
- Llamar a la función recursiva
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ code to solve the above problem #include <algorithm> #include <cmath> #include <cstdio> #include <iostream> #include <vector> using namespace std; // Recursive program to find count of // all combinations of at most K // digits with sum N int rec(vector<int>& arr, int i, int k, int c, int n, int& ans, int sum) { // Base case 1 if (sum == n && c <= k) { ans++; return ans; } // Base case 2 if (i >= arr.size() || sum > n || c > k) return ans; // Consider arr[i] into current selection // and call recursive function ans = rec(arr, i + 1, k, c + 1, n, ans, sum + arr[i]); // Do not consider arr[i] into current // selection and call recursive function ans = rec(arr, i + 1, k, c, n, ans, sum); return ans; } // Function to solve the problem // and print the count of combinations int combinationSum(int k, int n) { vector<int> arr(9, 0); for (int i = 1; i <= 9; i++) arr[i - 1] = i; int ans; // Recursive function call ans = rec(arr, 0, k, 0, n, ans, 0); return ans; } // Driver Code int main() { int N = 9, K = 3; cout << combinationSum(K, N) << endl; return 0; }
Java
// JAVA code to solve the above problem import java.util.*; class GFG { // Recursive program to find count of // all combinations of at most K // digits with sum N public static int rec(int[] arr, int i, int k, int c, int n, int ans, int sum) { // Base case 1 if (sum == n && c <= k) { ans++; return ans; } // Base case 2 if (i >= arr.length || sum > n || c > k) return ans; // Consider arr[i] into current selection // and call recursive function ans = rec(arr, i + 1, k, c + 1, n, ans, sum + arr[i]); // Do not consider arr[i] into current // selection and call recursive function ans = rec(arr, i + 1, k, c, n, ans, sum); return ans; } // Function to solve the problem // and print the count of combinations public static int combinationSum(int k, int n) { int[] arr = new int[9]; for (int i = 0; i < 9; i++) { arr[i] = 0; } for (int i = 1; i <= 9; i++) arr[i - 1] = i; int ans = 0; // Recursive function call ans = rec(arr, 0, k, 0, n, ans, 0); return ans; } // Driver Code public static void main(String[] args) { int N = 9, K = 3; System.out.println(combinationSum(K, N)); } } // This code is contributed by Taranpreet
Python3
# python3 code to solve the above problem # Recursive program to find count of # all combinations of at most K # digits with sum N def rec(arr, i, k, c, n, ans, sum): # Base case 1 if (sum == n and c <= k): ans += 1 return ans # Base case 2 if (i >= len(arr) or sum > n or c > k): return ans # Consider arr[i] into current selection # and call recursive function ans = rec(arr, i + 1, k, c + 1, n, ans, sum + arr[i]) # Do not consider arr[i] into current # selection and call recursive function ans = rec(arr, i + 1, k, c, n, ans, sum) return ans # Function to solve the problem # and print the count of combinations def combinationSum(k, n): arr = [0 for _ in range(9)] for i in range(1, 10): arr[i - 1] = i ans = 0 # Recursive function call ans = rec(arr, 0, k, 0, n, ans, 0) return ans # Driver Code if __name__ == "__main__": N, K = 9, 3 print(combinationSum(K, N)) # This code is contributed by rakeshsahni
C#
// C# code to solve the above problem using System; class GFG { // Recursive program to find count of // all combinations of at most K // digits with sum N static int rec(int[] arr, int i, int k, int c, int n, int ans, int sum) { // Base case 1 if (sum == n && c <= k) { ans++; return ans; } // Base case 2 if (i >= arr.Length || sum > n || c > k) return ans; // Consider arr[i] into current selection // and call recursive function ans = rec(arr, i + 1, k, c + 1, n, ans, sum + arr[i]); // Do not consider arr[i] into current // selection and call recursive function ans = rec(arr, i + 1, k, c, n, ans, sum); return ans; } // Function to solve the problem // and print the count of combinations static int combinationSum(int k, int n) { int[] arr = new int[9]; for (int i = 0; i < 9; i++) { arr[i] = 0; } for (int i = 1; i <= 9; i++) arr[i - 1] = i; int ans = 0; // Recursive function call ans = rec(arr, 0, k, 0, n, ans, 0); return ans; } // Driver Code public static int Main() { int N = 9, K = 3; Console.WriteLine(combinationSum(K, N)); return 0; } } // This code is contributed by Taranpreet
Javascript
<script> // JavaScript code for the above approach // Recursive program to find count of // all combinations of at most K // digits with sum N function rec(arr, i, k, c, n, ans, sum) { // Base case 1 if (sum == n && c <= k) { ans++; return ans; } // Base case 2 if (i >= arr.length || sum > n || c > k) return ans; // Consider arr[i] into current selection // and call recursive function ans = rec(arr, i + 1, k, c + 1, n, ans, sum + arr[i]); // Do not consider arr[i] into current // selection and call recursive function ans = rec(arr, i + 1, k, c, n, ans, sum); return ans; } // Function to solve the problem // and print the count of combinations function combinationSum(k, n) { let arr = new Array(9).fill(0); for (let i = 1; i <= 9; i++) arr[i - 1] = i; let ans = 0; // Recursive function call ans = rec(arr, 0, k, 0, n, ans, 0); return ans; } // Driver Code let N = 9, K = 3; document.write(combinationSum(K, N) + '<br>'); // This code is contributed by Potta Lokesh </script>
8
Complejidad de tiempo: O(10^2)
Espacio auxiliar: O(10^2)