排列的递归解决方案

时间:2014-02-17 17:35:13

标签: c++ algorithm recursion

嘿我有一个问题,我需要创建两个函数,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。

我已经完成了计数,但我完全停留在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;
    }
}

1 个答案:

答案 0 :(得分:1)

在不考虑排列的情况下计算的想法是仅考虑有序解决方案。

除了n之外,还要传递附录必须具有的最小值xmin。例如

3 = 1 + 2

没问题(因为2&gt; = 1),但是

3 = 2 + 1

是不可接受的(因为1&lt; 2)。

因此,我们的想法是编写一个函数来回答“在第一个附录中有多少与非递减项相加的和可以给出规定的total不小于min_addendum?”。

  1. 如果min_addendum大于total,则答案为0
  2. 如果total为1,那么只有一笔款项
  3. 否则第一个可能的总和是total,那么你应该算作总和
    • min_addendum +其他非递减字词的总和,第一个不低于min_addendum总计total-min_addendum
    • min_addendum+1 +其他非递减字词的总和,第一个不低于min_addendum+1总计total-min_addendum-1
    • min_addendum+2 +其他非递减字词的总和,第一个不低于min_addendum+2总计total-min_addendum-2
    • ...