leetcode 600 Count number of binary strings without consecutive 1 不出现连续1二进制数量
2017-12-21 09:06
567 查看
Given a positive integer N, count all possible distinct binary strings of length N such that there are no consecutive 1’s.
Examples:
Input: N = 2
Output: 3
// The 3 strings are 00, 01, 10
Input: N = 3
Output: 5
// The 5 strings are 000, 001, 010, 100, 101
思路是用DP,考虑从n位增加一位到n+1位的情况。如果首位是0,那么第n+1位的首位既可以是0,也可以是1,因为都不会产生连续的1;如果首位是1,那么只能生成首位是0的n+1位数,才能避免出现连续的1。
用zeros记录首
代码如下:
Examples:
Input: N = 2
Output: 3
// The 3 strings are 00, 01, 10
Input: N = 3
Output: 5
// The 5 strings are 000, 001, 010, 100, 101
思路是用DP,考虑从n位增加一位到n+1位的情况。如果首位是0,那么第n+1位的首位既可以是0,也可以是1,因为都不会产生连续的1;如果首位是1,那么只能生成首位是0的n+1位数,才能避免出现连续的1。
用zeros记录首
代码如下:
// C++ program to count all distinct binary strings // without two consecutive 1's #include <iostream> using namespace std; int countStrings(const int n) { vector<int> a(n), b(n); a[0] = b[0] = 1; for (int i = 1; i < n; i++) { a[i] = a[i - 1] + b[i - 1]; b[i] = a[i - 1]; } return a[n - 1] + b[n - 1]; } // Driver program to test above functions int main() { cout << countStrings(3) << endl; return 0; }
相关文章推荐
- geeksforgeeks Count number of binary strings without consecutive 1’s
- geeksforgeeks Count number of binary strings without consecutive 1′s
- 在排序数组中的出现次数 Count the number of occurrences in a sorted array
- LeetCode 562. Longest Line of Consecutive One in Matrix(在矩阵中最长的连续1)$
- [LeetCode] Binary Tree Longest Consecutive Sequence II 二叉树最长连续序列之二
- [LeetCode]485. Max Consecutive Ones(最大连续为1的数量)
- 第十五周:( LeetCode600) Non-negative Integers without Consecutive Ones(c++)
- [LeetCode] Number of Boomerangs 回旋镖的数量
- LeetCode "Count of Smaller Number After Self"
- Count occurrences of a number in a sorted array with duplicates using Binary Search
- [分析总结:leetcode-Number of Digit One]寻找整数1到n之间所有数字中1出现的次数
- [LeetCode] Binary Tree Longest Consecutive Sequence II 二叉树最长连续序列之二
- python int to binary and count the number of 1
- leetcode 600. Non-negative Integers without Consecutive Ones 非负整数不包括连续的1 + DP动态规划
- leetcode解题之191 # Number of 1 Bits Java版 (整数对应的二进制中1的个数)
- [LeetCode] Minimum Number of Arrows to Burst Balloons 最少数量的箭引爆气球
- Distinct binary strings of length n with no consecutive 1s
- [LeetCode 315] Count of Smaller Numbers After Self (树状数组 Binary Indexed Tree)
- [LeetCode] Number of Segments in a String 字符串中的分段数量
- Leetcode 600 Non-negative Integers without Consecutive Ones