整数拆分问题

//整数拆分问题:编写一个程序,找出一个正整数的所有可能拆分方式。例如,对于正整数 4,有以下拆分方式:1 + 1 + 1 + 1、1 + 1 + 2、1 + 3、2 + 2、4。
#include<iostream>
#include<stack>
#include <vector>
#include<string>
#include<algorithm>
#include<unordered_map>
#include <climits>
#include<queue>
#include<unordered_set>
#include<cctype>
#include <sstream>
#include<set>
using namespace std;
#define maxsize 100
void dfs(vector<vector<int>>& m, vector<int>& f, int k, int n, int cnt) {
    if (cnt == n) {
        m.push_back(f);
        return;
    }
    if (cnt > n) return;
    for (int i = k; i <= n; ++i) {
        f.push_back(i);
        dfs(m, f, i, n, cnt + i);
        f.pop_back();
    }
}

vector <vector<int>> solve(int n) {
    vector <vector<int>> m;
    vector<int> f;
    int cnt = 0;
    dfs(m, f, 1, n,cnt);
    return m;
}
int main() {
    vector <vector<int>> m = solve(4);
    for (auto a : m) {
        for (auto b : a) {
            cout << b << " ";
        }
        cout << endl;
    }
    return 0;
}

这其实是一个背包问题,感兴趣的就开始学习吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值