2018年南京大学夏令营机试-1

2018年南京大学夏令营机试-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
中文题意:
给定一个正整数n(3≤n≤90),数出长度为n的所有可能的不同二进制串的个数,使得串中没有连续的1出现。
解题思路:
设a[i]为长度为i的二进制串且不含有连续的1;
则a[1]=2 //0,1
a[2]=3 //00,01,10
若a[i]的第i位为0,那么第i-1位可以是0也可以是1,此种情况的二进制串有a[i-1]个;
若a[i]的第i位为1,那么第i-1位必为0,第i-2位可以是0或1,此种情况的二进制串有a[i-2]个。
所以当n>=3时,a[i]=a[i-1]+a[i-2];

AC代码

/*给定一个正整数n(3≤n≤90),数出长度为n的所有可能的不同二进制串的个数,使得串中没有连续的1出现。*/
#include<iostream>
using namespace std;
long long a[91];//注意数据类型
int main(){
	int n;
	cin >> n;
	a[1] = 2;
	a[2] = 3;
	if (n >= 3){
		for (int i = 3; i <= n; i++){
			a[i] = a[i - 1] + a[i - 2];
		}
		cout << a[n] << endl;
	}
	return 0;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值