【发布时间】:2014-02-18 09:10:55
【问题描述】:
嘿,我有一个问题,我需要创建两个函数,countWithPerms() 和 ignorePerms() 这两个函数必须是递归解决方案。 countWithPerms() 将计算实际排列的数量,而 ignorePerms() 将只计算重复排列的数量。
所以一个例子是找到数字 3 的排列。所以如果我将 3 传递给函数 countWithPerms() 会发现 3 = (2 + 1) = (1 + 2) = (1 + 1 + 1 ),所以 countWithPerms(3) 为 3,因为它计算了 3 种方式来求和 3。而 countIgnorePerms(3) 为 2,因为 (1 + 2) 和 (2 + 1),都不会计入 countWithPerms,因为它们是刚才写的顺序相反。
一个很大的例子是 countWithPerms(7) 是 63,而 countIgnorePerms(7) 是 14。
我已经完成了 countwithPerms,但我完全卡在 countIgnorePerms 上。
int countWithPerms( int n)
{
if(n == 1)
return 0;
else
n--;
return (countWithPerms(n) + 1) +
(countWithPerms(n));
}
int ignorePerms(int sum, int xmin){
if(sum == 1)
return 0;
else
for(int i=0; i<sum;i++){
sum += sum-xmin;
2*ignorePerms(sum,xmin)+1;
return sum;
}
}
【问题讨论】:
-
您计算的是分区,而不是排列。
-
ignorePerms() 被称为integer partition,countWithPerms() 被称为composition of integer。
-
我认为你是在排列的地方计算操作。
-
假设您的函数是正确的,您确实应该将 return 语句简化为
2*countWithPerms(n)+1- 您目前使用的是指数算法而不是线性算法。 -
@Dukeling:实际上对于“带有排列”的版本,答案是一个微不足道的封闭形式(只需考虑 n
1并计算您可以在 @987654326 中放置“障碍”的不同方式@一个数字和下一个数字之间的位置)...