整数分割——DFS回溯

一、输出效果

PS D:\cpp_works\OJ\build> ."D:/cpp_works/OJ/build/main.exe" 
5
5=1+1+1+1+1
5=1+1+1+2  
5=1+1+3
5=1+2+2
5=1+4
5=2+3
5=5

即输出5的所有求和的组合方式,不允许重复组合,如5=2+3和5=3+2是重复的。输出结果字符串需按字典序排序。

 二、代码实现

#include <bits/stdc++.h>

using namespace std;

static bool cmp(const string& str1, const string& str2)
{
    int i = 0;
    while (i < str1.size() && i < str2.size()) {
        if (str1[i] > str2[i]) {
            return false;
        } else if (str1[i] < str2[i]) {
            return true;
        }
        i++;
    }
    if (str1.size() == str2.size()) {
        return false;
    } else if (str1.size() > str2.size()) {
        return false;
    } else {
        return true;
    }
}

class Solution32 {
public:
    int n;
    vector<string> ret;

    void solve()
    {
        int n;
        while (cin >> n) {
            ret.clear();
            vector<int> vec;
            this->n = n;
            dfs(n, n, vec);
            sort(ret.begin(), ret.end(), cmp);
            for (const auto& it : ret) {
                cout << it << endl;
            }
        }
    }

    void dfs(int i, int j, vector<int>& vec)
    {
        if (j == 0) {
            return;
        } else if (i == 1 && j >= 1) {
            vec.push_back(1);
            show(vec, n);
            vec.pop_back();
            return;
        }
        if (i < j) {
            dfs(i, i, vec);
        } else if (i == j) {
            dfs(i, j - 1, vec);
            vec.push_back(j);
            show(vec, n);
            vec.pop_back();
        } else if (i > j) {
            // dp[i][j-1]
            dfs(i, j - 1, vec);
            // dp[i-j][j]
            vec.push_back(j);
            dfs(i - j, j, vec);
            vec.pop_back();
        }
    }
    void show(const vector<int>& vec, int n)
    {
        stringstream ss("");
        streambuf* old = cout.rdbuf();
        cout.rdbuf(ss.rdbuf());
        cout << n << "=";
        for (auto it = vec.rbegin(); it < vec.rend() - 1; it++) {
            cout << *it << "+";
        }
        cout << *(vec.rend() - 1);
        cout.rdbuf(old);
        ret.push_back(ss.str());
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值