[英]Print number of ways for non-consecutive one's
Given a positive integer N, print all integers between 1 and 2^N such that there is no consecutive 1's in its Binary representation. 给定正整数N,请打印1到2 ^ N之间的所有整数,以使其二进制表示形式中没有连续的1。
I have below code but it is printing duplicate sometimes. 我有以下代码,但有时会打印重复的代码。 Is it possible to print without duplicates?
是否可以不重复打印?
#include <stdio.h>
int a[100];
void foo(int i, int size)
{
if (i >= size) {
int i;
for (i=0;i<size;i++)
printf("%d\n", a[i]);
printf("----\n");
return;
}
if (a[i-1] == 1 || a[i-1] == 0)
a[i] = 0;
foo(i+1, size);
if (a[i-1] == 0)
a[i] = 1;
foo(i+1, size);
}
int main(void) {
int i = 0;
int size = 5;
a[i] = 1;
foo(1, size);
return 0;
}
I have this http://ideone.com/cT4Hco python program which uses hash maps to print the elements but I think we can do this without hashmaps also. 我有这个http://ideone.com/cT4Hco python程序,该程序使用哈希图来打印元素,但我认为我们也可以在没有哈希图的情况下执行此操作。
Couple of notes: 几个注意事项:
[0, n-1]
in array a
a
中处于[0, n-1]
范围内 a[0]
to 1
since a[0] = 0
is also a valid case. a[0]
初始化为1
因为a[0] = 0
也是有效的情况。 if (a[i-1] == 1 || a[i-1] == 0)
is redundant if (a[i-1] == 1 || a[i-1] == 0)
是多余的 Code: 码:
#include <stdio.h>
int a[100];
void foo(int i, int size)
{
if (i >= size) {
int i;
for (i=0;i<size;i++)
printf("%d ", a[i]);
printf("\n----\n");
return;
}
a[i] = 0;
foo(i+1, size);
if ( i == 0 || a[i-1] == 0) {
a[i] = 1;
foo(i+1, size);
}
}
int main(void) {
int i = 0;
int size = 5;
foo(0, size);
return 0;
}
You might also want to filter the solution 0 0 0 ... 0
during the printing since you need only the numbers from 1
to 2^n
. 您可能还需要在打印期间过滤解决方案
0 0 0 ... 0
,因为只需要1
到2^n
的数字即可。 If 2^n
is included you should also print it. 如果包含
2^n
则还应该打印它。 The backtracking considers the numbers 0, ...., 2^n-1
回溯考虑数字
0, ...., 2^n-1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.