分解的正整数到多个整数这样一笔保持原来的多个、整数、分解、正整数

2023-09-11 05:01:13 作者:好记的2个字的

得到了一个面试问题的今天,这我无法解决 寻找您的建议同样

Got an interview question today,which i was unable to solve Looking for your advice on same

的正整数中号分解为一组唯一的正整数,其总和为M 例如:7 = 1 + 6 = 2 + 5 = 3 + 4 = 1 + 2 + 4

需要编写一个函数,它计算所有这些独特的组合

Need to write a function which calculates all such unique combinations

推荐答案

您需要打印出来?那么,这样的事情:

you need to print them? then, something like this:

int a[100]; a[0] = 0; //to store composition

void rec(int x, int p) {
   for ( int i = a[p-1]+1; i <= x; i++ )
       if (x - i > i ) {
           a[p] = i;
           rec(x - i, p+1);
        } else {
           a[p] = x;
           //print if needed
           for ( int j = 1; j <= p; j++ )
               cout << a[j] << ' ';
           cout << endl;
           return;
        }
}

和不是打电话

rec(n, 1);