js数组合并数量相加_步数问题| 找到可能的组合数量以达到最后一步

js数组合并数量相加

Problem statement:

问题陈述:

You are trying to climb on a staircase. There are N number of steps. You can only climb one or two steps at one time. Now you have to find out the number of possible combinations to reach the final step.

您正在尝试爬楼梯。 有N个步骤。 您一次只能爬一两步。 现在,您必须找出可能的组合数量才能到达最后一步。

Input:
First-line contains T Testcases,
T no. of lines along with the step count(N).

E.g.
3
4
5
6

Output:
Print the number of possible valid steps 
to reach the last step.

Example

T = 3

Input:
4
Output:
5

Input:
5
Output:
8

Input:
6
Output:
13

Explanation with example:

举例说明:

To find out the possible combination to reach the last step is a problem of combination. We are using the Dynamic programming approach to solve it with less time complexity.

找出可能的组合以达到最后一步是组合的问题。 我们正在使用动态编程方法以更少的时间复杂性来解决它。

To solve this problem, we will follow these steps,

为了解决这个问题,我们将按照以下步骤操作,

  1. We need an array of size equals the number of steps N.

    我们需要一个大小等于步骤N的数组。

  2. We initialize the first step with the value one.

    我们使用值one初始化第一步。

  3. Initialize the second step with two because you can take two steps to reach the second step or you can directly move to the second step. Therefore, in the second step there in two possibilities.

    用两个值初始化第二步,因为您可以分两步到达第二步,也可以直接移至第二步。 因此,在第二步中存在两种可能性。

  4. For the steps those are greater than the 2nd there is two possibilities,

    对于步骤那些比2更大的第二有两种可能性,

    1. To reach the ith step, we can go from the (i-1) step.
    2. 为了达到 i 步骤中,我们可以去从(I-1)步。
    3. To reach the ith step, we can go from the (i-2) step.
    4. 为了达到 i 步骤中,我们可以去从(I-2)步。

Let f(i)= no. Of possible combination to reach the ith step.
f(i)= f(i-1) +f(i-2)


C++ Implementation:

C ++实现:

#include <bits/stdc++.h>
using namespace std;

int count(int num)
{
    int arr[num];
    arr[0] = 1;
    arr[1] = 2;
    for (int i = 2; i < num; i++) {
        arr[i] = arr[i - 1] + arr[i - 2];
    }
    return arr[num - 1];
}

int main()
{
    int t;
    
    cout << "Testcase : ";
    cin >> t;
    
    while (t--) {
        int num;
    
        cout << "Enter the Steps : ";
        cin >> num;
    
        cout << "Step Count : " << count(num) << endl;
    }
    
    return 0;
}

Output

输出量

Testcase : 3
Enter the Steps : 5
Step Count : 8
Enter the Steps : 10
Step Count : 89
Enter the Steps : 7
Step Count : 21


翻译自: https://www.includehelp.com/icp/step-count-problem.aspx

js数组合并数量相加

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值