这道题是不是不用回溯
查看原帖
这道题是不是不用回溯
932039
lzy20091001楼主2023/7/20 09:59

看了一下题解,好像都在用回溯。各位大佬们看看这道题是不是不用回溯?

#include <iostream>
#include <algorithm>
using namespace std;

int n;
int a[10];

void dfs(int dep, int x)
{
    if (x == n)
    {
        if (dep != 2)
        {
            for (int i = 1; i < dep - 1; i++)
                cout << a[i] << "+";
            cout << a[dep - 1] << "\n";
        }
    }
    else
        for (int i = max(a[dep - 1], 1); i <= n - x; i++)
        {
            a[dep] = i;
            dfs(dep + 1, x + a[dep]);
        }
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    
    cin >> n;
    dfs(1, 0);
    return 0;
}
2023/7/20 09:59
加载中...