求正整数的所有分割并输出II

求正整数的所有分割并输出II

函数Part(N,M)能得到N不大于M的所有分割的集合。

#include<iostream>
#include<vector>
#include<algorithm>
#include<iterator>

using namespace std;

/* 求正整数的所有分割并输出: case 1: N>M, Part(N,M)为集合Part(N,M-1)并上M+Part(N-M,M)集合 case 2: N==M, Part(N,M)为集合Part(N,M-1)并上{M} case 3: N<M Part(N,M)为集合Part(N,N) case 4: N==1 Part(N,M)为集合{1} case 5: M==1 Part(N,M)为集合{1,1,1...,1}(共N个1) */
vector<vector<int>> Part(int N ,int M){

    vector<vector<int>> ret;

    // 1个1
    if (N == 1)
    {
        vector<int> cur;
        cur.push_back(1);
        ret.push_back(cur);
        return ret;
    }

    // N个1
    if (M == 1)
    {
        vector<int> cur;
        for (int i(0); i < N; i++)
        {
            cur.push_back(1);
        }
        ret.push_back(cur);
        return ret;
    }

    if (N < M)
    {
        return Part(N,N);
    }

    if (N == M)
    {
        ret = Part(N, M - 1);
        vector<int> cur;
        cur.push_back(M);
        ret.push_back(cur);
        return ret;
    }

    // N>M
    ret = Part(N, M - 1);
    vector<vector<int>> temp = Part(N - M, M);
    for (vector<int> &v : temp)
    {
        v.push_back(M);
        ret.push_back(v);
    }

    return ret;
}


int main(){

    vector<vector<int>> result;
    int n;
    cout << "请输入想要分割的正整数n:" << endl;
    cin >> n;

    result = Part(n, n);
    cout << "所有分割的结果:" << endl;
    cout << endl;
    for (int i(0); i < result.size(); i++){
        cout << "{";
        cout << result[i][0];
        for (int j(1); j < result[i].size(); j++)
            cout << "," << result[i][j];
        cout << "}";
        cout << endl;
    }
    cout << endl;
    cout << "划分数目:" << result.size() << endl;
    cout << endl;
    system("pause");

    return 0;
}
点赞