快速提问。我试图找到所有可能的数字组合,以达到c + +中的给定总和。您是否认为有办法在仍使用递归函数的同时改进我的代码?这是我到目前为止的内容:
void kombinacii(int a[], int index, int num, int decrement) {
if (decrement < 0) {
return;
}
if (decrement == 0){
cout<<"\t N = ";
for (int i = 0; i < index; i++)
cout << a[i] << " ";
cout << endl;
return;
}
int prev;
if(index == 0)
prev = 1;
else
prev = a[index-1];
for (int k = prev; k < num ; k++) {
a[index] = k;
kombinacii(a, index + 1, num, decrement - k);
}
}
void namiraneNaKombinaciq(int n) {
int a[50];
kombinacii(a, 0, n, n);
}
int main() {
int n;
cout<<"Choose a natural number (N): \n";
cin>>n;
namiraneNaKombinaciq(n);
system("pause");
}
我当前的输出是:
N = 1 1 1
有没有办法使它看起来像这样:
N = 1 + 1 + 1