分解的正整数到多个整数这样一笔保持原来的 [英] decomposing positive integer into more integers such that sum same as original

查看:138
本文介绍了分解的正整数到多个整数这样一笔保持原来的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

得到了一个面试问题的今天,这我无法解决 寻找您的建议同样

Got an interview question today,which i was unable to solve Looking for your advice on same

  • 的正整数中号分解为一组唯一的正整数,其总和为M
  • 例如:7 = 1 + 6 = 2 + 5 = 3 + 4 = 1 + 2 + 4

需要编写一个函数,它计算所有这些独特的组合

Need to write a function which calculates all such unique combinations

推荐答案

您需要打印出来?那么,这样的事情:

you need to print them? then, something like this:

int a[100]; a[0] = 0; //to store composition

void rec(int x, int p) {
   for ( int i = a[p-1]+1; i <= x; i++ )
       if (x - i > i ) {
           a[p] = i;
           rec(x - i, p+1);
        } else {
           a[p] = x;
           //print if needed
           for ( int j = 1; j <= p; j++ )
               cout << a[j] << ' ';
           cout << endl;
           return;
        }
}

和不是打电话

rec(n, 1);

这篇关于分解的正整数到多个整数这样一笔保持原来的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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