将一个数m分解为n个不同的数之和(积)

简单递归求解.

#include "iostream"
#include "vector"
#include "algorithm"
using namespace std;
#define N 4
vector<int>record;
vector<vector<int>> result;
void print()
{
    for (auto it : record)
        cout << it<<"\t";
    cout << "\n==============================="
        <void func(int n, int m,int min_el)
{
    static int index = 0;
    if (n == 2)
    {
        for (int i = min_el+1; i < m / 2; ++i)
        {
            record.push_back(i);
            record.push_back(m-i);
            result.push_back(record);
            cout << "case: " << ++index<return;
    }
    for (int beg = min_el+1; beg < m / n; ++beg)
    {
        record.push_back(beg);
        func(n - 1, m - beg, beg);
        record.pop_back();
    }
}
int main()
{
    func(N,20,0);
    return 0;
}

部分结果:
将一个数m分解为n个不同的数之和(积)_第1张图片

==========================================================

#include "iostream"
#include "vector"
#include "cmath"
#include "algorithm"
using namespace std;
#define N 4
vector<int>record;
vector<vector<int>> result;
void print()
{
    for (auto it : record)
        cout << it<<"\t";
    cout << "\n==============================="
        <void func(int n, int m,int min_el)
{
    static int index = 0;
    if (n == 2)
    {
        for (int i = min_el+1; i*i < m; ++i)
        {
            record.push_back(i);
            record.push_back(m/i);
            if (!(m%i))//i是m的约数
            {   
                result.push_back(record);
            cout << "case: " << ++index<return;
    }
    for (int beg = min_el+1; pow(beg,n) < m; ++beg)
    {
        record.push_back(beg);
        if (!(m%beg))
        func(n - 1, m/beg, beg);
        record.pop_back();
    }
}
int main()
{

    func(N,48*9,0);
    return 0;
}

将一个数m分解为n个不同的数之和(积)_第2张图片

你可能感兴趣的:(笔试面试)