【问题标题】:Recursion: Find the sum of all possible k-permutations of a given digit array递归:找到给定数字数组的所有可能 k 排列的总和
【发布时间】:2015-04-13 22:33:22
【问题描述】:

我遇到的问题是这样的:

对于给定的不同十进制数字 (0,1,2,3...,8,9) 的数组,编写一个递归函数,返回由给定数字组成的所有自然数的总和。例如。对于数组 {1,2} 你会得到 12 + 21 + 2 + 1 = 36

我的想法是如果你有一个数组 1,2,3

您将“搁置”最后一个数字并排列剩下的较小的集合,如下所示:

  1. 1 2 3
  2. 2 1 3
  3. 2 3
  4. 1 3
  5. 3

这将是 10 * [perm(1,2)] + 3 * (重复次数)

这是我在 c 中的代码:

#include <stdio.h>
#include <stdlib.h>

void swap(int *a,int *b)
{
int *temp=a;
    *a=*b;
    *b=*temp;
}

int rek(int n[], int d,int sum,int cnt)
{   cnt++;
if(d==0){return n[d];}
int i;
for(i=d;i>=0;i--)
{
    swap(&n[i],&n[d]);
    sum+=10+rek(n,d-1,sum,0)+n[d]*cnt;
    swap(&n[i],&n[d]);
}
return sum;
}


int main()
{
int a[9],k,i,s=0,error=0;
scanf("%d",&k);
for(i=0;i<k;i++)
{
    scanf("%d",&a[i]);
    if(i){if(a[i]==a[i-1]){error=1;} }
}
if(error){printf("Error!"); return 0;}

s+=rek(a,k-1,s,0);

printf("%d",s);

return 0;
}

似乎我的交换不起作用,我不知道为什么。我在 rek 函数中打印了数组,对于输入 {1,2},它应该是一次 {1,2},另一次是 {2,1},但我得到的是 {1,2},然后是 {2,2}。我环顾四周,但我唯一能找到的是所有可能组合的总和,总和为某个数字。我知道这可以在不使用某些组合公式的递归的情况下完成,但我对递归版本感兴趣。

【问题讨论】:

    标签: c recursion sum permutation


    【解决方案1】:
    void swap(int *a,int *b)
    {
    int *temp=a;
        *a=*b;
        *b=*temp;
    }
    

    这会将指针a 存储在temp 中,设置a 的值,然后读取temp 的值。它仍然指向同一个地方,现在它有了一个新的价值。您需要将值本身存储在临时变量中:

    void swap(int *a, int *b)
    {
        int temp = *a;
        *a = *b;
        *b = temp;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-05
      • 2013-02-03
      • 1970-01-01
      • 2019-05-24
      • 2021-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多