81 阶梯锻炼

2023-12-22 16:04:14

回溯

#include <iostream>
#include <vector>

using namespace::std;
using std::cout;
using std::cin; 

void jump(int n, int k, vector<int>& path, vector<vector<int>>& result) 
{
    if (n == 0) 
	{
        result.push_back(path);
        return;
    }
    for (int i = 1; i <= k && i <= n; i++) 
	{
        path.push_back(i);
        jump(n - i, k, path, result);
        path.pop_back();
    }
}

vector<vector<int>> exerciseWays(int n, int k) 
{
    vector<vector<int>> result;
    vector<int> path;
    jump(n, k, path, result);
    return result;
}

int main() 
{
    int n,k;
    cin>> n >> k;
    vector<vector<int>> result = exerciseWays(n, k);
    for (const auto& path : result) 
	{
        for (int i = 0; i < path.size(); i++) 
		{
            std::cout << path[i];
            if (i != path.size() - 1) {
                std::cout << " ";
            }
        }
        std::cout << "\n";
    }
    return 0;
}

文章来源:https://blog.csdn.net/qq_64654845/article/details/135152011
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。