18年机试(nju)

18年机试(nju)

  1. Count number of binary strings without consecutive 1’s
    Given a positive integer n(3≤n≤90), count all possible distinct binary strings of length n such that there are no consecutive 1’s .
    Examples:
    Input: 2
    Output: 3 // The 3 strings are 00, 01, 10

    Input: 3
    Output: 5 // The 5 strings are 000, 001, 010, 100, 101

a[i]表示长度为i的不含连续1的二进制串的个数

第i位为1,则第i-1位必为0,第i-2位可以为0或1,a[i]=a[i-2],最后两位为0 1
第i位为0,则第i-1位可以为0或1,a[i]=a[i-1]

递推方程:a[i]=a[i-2]+a[i-1], i>=3
边界条件:a[1]=2,a[2]=3

动态规划,时间复杂度为O(n)
能用动态规划就尽量不要用回溯法,回溯法容易超时

#include <iostream>

using namespace std;

long long a[91];

int main()
{
    int n;//3<=n<=90
    cin>>n;

    a[1]=2;
    a[2]=3;
    //初始化a[1]=2,a[2]=3
    //long long *a=new long long[n+2]{0,2,3};


    for(int i=3;i<=n;i++){
        a[i]=a[i-1]+a[i-2];
    }
    cout<<a[n]<<endl;
    return 0;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值