找出最多为 N 个数的所有有效组合
给定两个数字N和K ,任务是找到最多为 K个数字的所有有效组合,这些数字的总和为N使得以下条件为真:
- 仅使用数字 1 到 9。
- 每个号码最多使用一次。
返回所有可能的有效组合的列表
例子:
Input: K = 3, N = 7
Output:
1 2 4
1 6
2 5
3 4
7
Input: K = 3, N = 9
Output:
1 2 6
1 3 5
1 8
2 3 4
2 7
3 6
4 5
9
朴素方法:这个想法是创建一个从 1 到 9 的数字数组,并找到长度最多为 K 且总和为 N 的所有子序列。
时间复杂度: O(10^2)
辅助空间: O(10^2)
递归方法:该问题也可以使用递归解决,如下所示:
- 在 arr 中创建一个 1-9 的数字数组。
- 创建一个递归函数,该函数以当前索引为i 、当前总和为sum 、当前计数为c 、当前选择为temp 、当前结果向量为ans来迭代数组。
- 基本情况 1:如果 (sum == n && c <= k)
- 将 temp 向量插入到 ans 向量中
- 返回 ans 向量
- 基本情况 2:如果 (i >= arr.size() || sum > n || c > k)
- 在违反当前约束时返回 ans 向量
- 别的
- 将当前数组元素推入临时向量
- 调用递归函数
- 从向量中弹出当前元素
- 调用递归函数
下面是上述方法的实现:
C++
// C++ code to solve the above problem
#include
#include
#include
#include
#include
using namespace std;
// Recursive program to find
// all combinations of at most K
// digits with sum N
vector > rec(vector& arr, int i, int k,
int c, int n,
vector >& ans,
vector& temp, int sum)
{
// Base case 1
if (sum == n && c <= k) {
ans.push_back(temp);
return ans;
}
// Base case 2
if (i >= arr.size() || sum > n || c > k)
return ans;
// Insert arr[i] into current selection
// and call recursive function
temp.push_back(arr[i]);
ans = rec(arr, i + 1, k, c + 1, n, ans, temp,
sum + arr[i]);
// Remove arr[i] from current selection
// and call recursive function
temp.pop_back();
ans = rec(arr, i + 1, k, c, n, ans, temp, sum);
return ans;
}
// Function to solve the problem
// and print the list of combinations
void combinationSum(int k, int n)
{
vector arr(9, 0);
for (int i = 1; i <= 9; i++)
arr[i - 1] = i;
vector > ans;
vector temp;
// Recursive function call
ans = rec(arr, 0, k, 0, n, ans, temp, 0);
// Print the output[][] array
for (int i = 0; i < ans.size(); i++) {
for (auto x : ans[i])
cout << x << " ";
cout << endl;
}
}
// Driver Code
int main()
{
int N = 7, K = 3;
combinationSum(K, N);
return 0;
}
Python3
# python3 code to solve the above problem
# Recursive program to find
# all combinations of at most K
# digits with sum N
def rec(arr, i, k, c, n, ans, temp, sum):
# Base case 1
if (sum == n and c <= k):
ans.append(temp.copy())
return ans
# Base case 2
if (i >= len(arr) or sum > n or c > k):
return ans
# Insert arr[i] into current selection
# //and call recursive function
temp.append(arr[i])
ans = rec(arr, i + 1, k, c + 1, n, ans, temp,
sum + arr[i])
# Remove arr[i] from current selection
# and call recursive function
temp.pop()
ans = rec(arr, i + 1, k, c, n, ans, temp, sum)
return ans
# Function to solve the problem
# and print the list of combinations
def combinationSum(k, n):
arr = [0 for _ in range(9)]
for i in range(1, 10):
arr[i - 1] = i
ans = []
temp = []
# Recursive function call
ans = rec(arr, 0, k, 0, n, ans, temp, 0)
# Print the output[][] array
for i in range(0, len(ans)):
for x in ans[i]:
print(x, end=" ")
print()
# Driver Code
if __name__ == "__main__":
N, K = 7, 3
combinationSum(K, N)
# This code is contributed by rakeshsahni
输出
1 2 4
1 6
2 5
3 4
7
时间复杂度: O(10^2)
辅助空间: O(10^2)