【问题标题】:trying to solve dynamic programming试图解决动态规划
【发布时间】:2015-06-19 05:48:14
【问题描述】:

我遇到了一个已经结束的比赛的问题。下面是问题。

在Poornima 学院,PIET CS 部门正在从地下室搬到三楼。该部门的HOD正在设法找到到达三楼的方法。你得到了楼梯的数量,你必须帮助 HOD 找出他可以爬楼梯的方法的数量。 HOD 一次最多可以爬两个楼梯,最少可以爬零。

Input:The first line contains the number of test cases, T. 
T lines follow, each of which contains total number of stairs.

Output:
Print the total number of possible ways to climbing the stairs.

Constraints: 
1<=T<=100
1<=N<=100

Sample Input(Plaintext Link)
 3
1
2
4
Sample Output(Plaintext Link)
 1
2
5
Explanation
Input: n = 1
Output: 1
There is only one way to climb 1 stair

Input: n = 2
Output: 2
There are two ways: (1, 1) and (2,0)

Input: n = 4
Output: 5
(1, 1, 1, 1), (1, 1, 2,0), (2, 1, 1,0), (1, 2, 1,0), (2, 2,0,0) are the only four ways to climb stairs.

我确信可以通过使用 DP 来实现该解决方案。但我尝试过但失败了我是解决 DP 问题的新手。我该如何解决?

这是一种解决方案,但该 DP 公式是如何得出的?

#include<cstdio>
#include<iostream>
#include<vector>
#include<utility>
#include<string.h>
#include<algorithm>
#include<cmath>

#define LL long long int
#define s(a) scanf("%d",&a)

#define ss(a) scanf("%s",a)
#define w(t) while(t--)
#define f(i,n) for(i=0;i<n;i++)
#define fd(i,n) for(i=n-1;i>=0;i--)
#define p(a) printf("%d",a)

#define ps(a) printf("%s",a)
#define pc(a) printf("%c",a)
#define ent printf("\n")
bool wayToSort(int i, int j) { return i > j; }
using namespace std;
long long int dp[1005];
int main()
{   dp[0]=0;
    dp[1]=1;
    dp[2]=2;
    int t,i,j,n;
    for(i=3;i<=1000;i++)
    {
        dp[i]=dp[i-1]+dp[i-2];
    }
    s(t);
    w(t)
    {
        s(n);
        cout<<dp[n]<<endl;
    }
    return 0;
}

【问题讨论】:

  • 请在此处提出您的问题,而不是链接到外部网站。
  • 定义这样的循环或函数的目的是什么,从而使程序不可读?
  • @Blacktempel 这纯粹是为了一场比赛,即使迟到一秒也很重要,所以只是为了速度目的,它是这样定义的。
  • @HardeosinghSingh compile speed 在比赛中重要吗?
  • 感谢您的建议。我的错 :)

标签: c++ dynamic-programming


【解决方案1】:

嗯,这是一个非常普遍的动态规划难题......假设你在第 n 层楼梯,那么你可以去第 n 层楼梯的路数是到达第 n-1 层楼梯的路数,并且第n个楼梯! 为什么? 嗯,从第n-1个楼梯爬一个楼梯和从n-2个楼梯直接爬两个楼梯,我只能通过两种方式到达第n个楼梯!

Morover 我觉得你的问题陈述有问题,它说我们至少可以移动 0 步,这将导致到达某个楼梯的方法数无限!为什么?我可以简单地使用无限的步骤留在同一个楼梯上,然后移动到下一个!所以我假设你一次可以移动一两个楼梯

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-25
    • 2014-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    相关资源
    最近更新 更多