A floor of size 8x8 has to be covered by bricks of size 1x2. How many ways are there to layout bricks in the floor? Generalize the problem to the floor of size MxN and bricks of size PxQ each.
int foo(int n,int x,int y)
{
if(x>=n||y>=n)
return 0;
if(x==n-1&&y==n-1)
return 1;
return foo(n,x+2,y+0)+foo(n,x+1,y+1)+foo(n,x+0,y+1)+foo(n,x+0,y+2)+foo(n,x+1,y+0);
}
Showing posts with label recursion. Show all posts
Showing posts with label recursion. Show all posts
Jul 28, 2009
Feb 2, 2009
Given n pairs of parentheses. Write a program to print out all valid configrations. For example n=2, ()(), (()) are valid, but ))((, ())( are not.
Given n pairs of parentheses. Write a program to print out all valid configrations.
For example n=2, ()(), (()) are valid, but ))((, ())( are not.
foo(stack s, int count, int len)
{
if(count<0)
return ;
if(len==0)
{
if(count==0)
print s;
else return;
}
foo(s.push('('),count+1,len-1);
foo(s.push(')'),count-1.len-1);
}
For example n=2, ()(), (()) are valid, but ))((, ())( are not.
foo(stack s, int count, int len)
{
if(count<0)
return ;
if(len==0)
{
if(count==0)
print s;
else return;
}
foo(s.push('('),count+1,len-1);
foo(s.push(')'),count-1.len-1);
}
Jan 3, 2009
you are given a binary tree....write a code that returns the leaf node present at topmost level.... two leafs may be present at same level (take care
you are given a binary tree....write a code that returns the leaf node
present at topmost level....
two leafs may be present at same level
(take care of this condition)
use bfs
or
present at topmost level....
two leafs may be present at same level
(take care of this condition)
use bfs
or
int lowleaf(node *root)
{
if(root==NULL) return 0;
else
return 1+min(lowleaf(root->left),lowleaf(root->right));
}
Dec 28, 2008
An algorithm to find total number of unique path from (0,0) to (m,n) in an m*n grid . You are only allowed to move either RIGHT or DOWN . Each cell
An algorithm to find total number of unique path from (0,0) to (m,n) in an m*n grid . You are only allowed to move either RIGHT or DOWN . Each cell of grid is of dimension 1 * 1 .
Ex : 3 * 3 grid total number of unique path is 6 .
Ex : 3 * 3 grid total number of unique path is 6 .
int func(int m,int n)
{
/*if(m==0&&n==0)
return 1;
if(m<0||n<0)
return 0;*/
if(m==0||n==0)
return 1;
return func(m-1,n)+func(m,n-1);
}
Subscribe to:
Posts (Atom)