如何指示/打印基于斐波那契数字的程序的不同组合

How can I indicate/print the distinct combinations to this Fibonacci number-based program?

本文关键字:数字 程序 组合 于斐波 何指示 指示 打印      更新时间:2023-10-16

我正在构建一个函数,以确定人们可以爬到楼梯顶部的不同方式(可以攀登1或2步(。尽管我已经获得了打印几种方式的主要功能,但我对如何打印特定组合感到困惑,即有三种爬升的方法:(1,1,1,1(,(1,2(,(2,1(。

#include <iostream>
using namespace std;
int climbStairs(int n);
int main()
{
  int s = 4;
  cout << "There are " << climbStairs(s) << " ways to climb to the top: ";           
  return 0;
}
int climbStairs(int n)    
{    
  if(n == 0) return 0;
  if(n == 1) return 1;
    int one = 1;
    int two = 0;
    int result = 0;   
    for(int i = 1;i <= n;i++)
    {
       result = one + two;
       two = one;
       one = result;
    }   
    return result;
}

关于如何打印组合的任何解释都会有所帮助,非常感谢!

,而不是让变量onetwo是整数,而是将它们定义为"路径"集。然后,做同样的事情,除了 resultone,其中1附加到其中的所有"路径"加上 two,其中2个附加到其中的所有"路径"。

该算法看起来像这样(我建议在查看我的代码之前自己尝试一下(:

#include <set>
#include <string>
#include <iostream>
std::set<std::string> climbStairs(int n)
{
    if(n == 0)
        return {""};
    if(n == 1)
        return {"1"};
    std::set<std::string> one({"1"}), two({""}), result;
    for(int i = 2; i <= n; i++)
    {
        result.clear();
        for(const std::string &path : one)
        {
            result.insert(path + '1');
        }
        for(const std::string &path : two)
        {
            result.insert(path + '2');
        }
        two = move(one);
        one = move(result);
    }
    return one;
}
int main()
{
    std::set<std::string> s = climbStairs(5);
    for(const std::string &path : s)
    {
        std::cout << path << 'n';
    }
}

这是我知道的最好方法。