我需要编写函数作为赋值的一部分.. 我需要计算将n分成正整数之和的方法的数量,我不能用于while或goto
/*
* REQUIRES: n > 0
* EFFECTS: computes the number of ways to partition n into the sum of
* positive integers
* MUST be tree recursive
* Hint: Use a helper function that computes the number of ways to
* partition n using a bounded subset of integers. Then use logic
* similar to count_change() from lecture to divide partitions into
* those that use a specific item and those that do not.
*/
int num_partitions(int n);
我想办法打印它们但无法计算它,我的功能也需要循环。这是功能
void print(int n, int * a) {
int i ;
for (i = 0; i <= n; i++) {
printf("%d", a[i]);
}
printf("\n");
}
int integerPartition(int n, int * a, int level,int c){
int first;
int i;
if (n < 1)
{
return c;
}
a[level] = n;
print(level, a);
c++;
first = (level == 0) ? 1 : a[level-1];
for(i = first; i <= n / 2; i++){
a[level] = i;
integerPartition(n - i, a, level + 1,c);
}
}
int num_partitions(int n){
int * a = (int * ) malloc(sizeof(int) * n);
return integerPartition (n, a, 0,0);
}
请帮忙......
这是计数更改功能
int count_change(int amount, const int coins[], int num_coins) {
if (amount == 0) {
return 1;
} else if (amount < 0 || num_coins < 1) {
return 0;
} else {
return
count_change(amount - coins[num_coins - 1], coins, num_coins) +
count_change(amount, coins, num_coins - 1);
}
}
答案 0 :(得分:3)
你可以这样做:
#include <conio.h>
#include <iostream>
using namespace std;
int integerPartition(int n, int k);
int main()
{
int n;
cin>>n;
int k =n;
cout<<integerPartition(n,k);
getchar();
return 0;
}
int integerPartition(int n, int k)
{
if(k==0)
return 0;
if(n ==0)
return 1;
if(n<0)
return 0;
return integerPartition(n,k-1) + integerPartition(n-k,k);
}
灵感来自:http://www.programminglogic.com/integer-partition-algorithm/
或者您也可以使用:分区函数的递归公式,在上面给出 https://en.wikipedia.org/wiki/Partition_(number_theory)