1 条题解

  • 0
    @ 2025-3-9 14:43:20

    乱选枚举+最后检查

    #include <bits/stdc++.h>
    using namespace std;
    int n, r;
    int ans[10]; // ans[i] 记录第 i 层选了谁
    void dfs(int now)
    {
        if (now > r)
        {
            bool flag = true;
            for (int i = 2; i <= r; i++)
                if (ans[i - 1] >= ans[i])
                    flag = false;
            if (flag)
            {
                for (int i = 1; i <= r; i++)
                    cout << "  " << ans[i];
                cout << "\n";
            }
            return;
        }
        for (int i = 1; i <= n; i++)
        {
            ans[now] = i;
            dfs(now + 1);
        }
    }
    int main()
    {
        ios::sync_with_stdio(false);
        cin.tie(0);
        cin >> n >> r;
        dfs(1);
        return 0;
    }
    

    保证每一步都合法

    #include <bits/stdc++.h>
    using namespace std;
    int n, r;
    int ans[10]; // ans[i] 记录第 i 层选了谁
    void dfs(int now)
    {
        if (now > r)
        {
            for (int i = 1; i <= r; i++)
                cout << "  " << ans[i];
            cout << "\n";
            return;
        }
        for (int i = ans[now - 1] + 1; i <= n; i++)
        {
            ans[now] = i;
            dfs(now + 1);
        }
    }
    int main()
    {
        ios::sync_with_stdio(false);
        cin.tie(0);
        cin >> n >> r;
        dfs(1);
        return 0;
    }
    

    参数传状态(TLE/MLE/RE 警告)

    #include <bits/stdc++.h>
    using namespace std;
    int n, r;
    void dfs(int now, int pre, string s)
    {
        if (now > r)
        {
            cout << s << "\n";
            return;
        }
        for (int i = pre + 1; i <= n; i++)
            dfs(now + 1, i, s + "  " + (char)(i + '0'));
    }
    int main()
    {
        ios::sync_with_stdio(false);
        cin.tie(0);
        cin >> n >> r;
        dfs(1, 0, "");
        return 0;
    }
    
    • 1

    信息

    ID
    536
    时间
    1000ms
    内存
    128MiB
    难度
    6
    标签
    (无)
    递交数
    121
    已通过
    38
    上传者