递归函数计数和打印 1 到 n-1 的分区 [英] Recursive function counting and printing partitions of 1 to n-1

查看:82
本文介绍了递归函数计数和打印 1 到 n-1 的分区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个递归函数(它必须是递归的)来打印出 1 到 n-1 的分区和分区数.例如,总和为 4 的 4 个组合:

I am trying write a recursive function(it must be recursive) to print out the partitions and number of partitions for 1 to n-1. For example, 4 combinations that sum to 4:

1 1 1 1
1 1 2
1 3
2 2

我只是在使用该功能时遇到了很多麻烦.下面的这个功能不起作用.有人可以帮我吗?

I am just having much trouble with the function. This function below doesn't work. Can someone help me please?

 int partition(int n, int max)
{

  if(n==1||max==1)
    return(1);
  int counter = 0;
  if(n<=max)
    counter=1;
  for(int i = 0; n>i; i++){
          n=n-1;
          cout << n << "+"<< i <<"\n";
          counter++;
          partition(n,i);         
        }

  return(counter);
}

推荐答案

这是一个简单的伪代码,看你懂没有,初始调用是用recPartition(n,1)

This is a simple pseudocode , see if you understand , initial call is with recPartition(n,1)

int A[100]
int n
int cnt = 0
recPartition(int remaining,int indx)
    if(remaining <0 )
       return
    if(remaining == 0)
        print from 1 to indx in A
        ++cnt
        return
    for i from 1 to remaining
         if(i!=n)
             A[indx] = i
             recPartition(remaining-i,indx+1) 

这篇关于递归函数计数和打印 1 到 n-1 的分区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆