在 c 中给定一个固定数的情况下,找到所有可能的加法和组合(给定一个总和,找到它的可能的加法和排列

Finding all possible addition and combination given a fixed number in c ( given a sum, find the possible addition and permutation of it.)

本文关键字:一个 排列 组合 情况下 有可能      更新时间:2023-10-16

我正在寻找所有可能的数字组合以及它们在固定大小的数组中的排列。例如,我有总共 5 个,所需的输出将是

5 0 0 0

05 0 0

0 05 0

0 00 5

4 1 0 0

1 4 0 0

1 0 4 0

1 0 0 4

01 4 0

等等...这可能吗?

使用递归:

void find(int remain, int depth, vector<int> v) {
if (depth == 4) {
if (remain == 0){
for (int i = 0 ;i < 4; i++) {
cout << v[i];
}
cout<<endl;
}
return;
}
for (int i = 0; i <= remain; i++) {
v.push_back(i);
find(remain-i, depth+1, v);
v.pop_back();
}
}