Uploaded by noob bot

TUF

advertisement
 1) Recursion : when a fun calls itself until a specified condition is met.
2) Print name N times: void f(i, n)
{
if (i > n)
return;
print('raj');
f(i+1, n);
}
main()
{
int n;
cnt >> n;
f(1,n);
}
3) Print 1 --> N:
f(i, n)
{
if (i > n)
return;
print(i);
f(i+1, n);
}
main()
{
input(n);
f(1, n);
}
4) Print N --> 1:
f(i, n)
{
if(i < 1)
return;
print(i);
f(i-1, n);
}
main()
{
input(n);
f(n, n);
}
5) Print linearly 1 to n using backtracking:
f(i, n)
{
if(i < 1)
return;
f(i-1, n);
print(i);
}
main()
{
input(n);
f(n, n);
} 6) Print linearly n to 1 using backtracking:
f(i, n)
{
if(n < i)
return;
f(i+1, n);
print(i);
}
main()
{
input(n);
f(1,n);
}
7) print sum of first N numbers:
a) Parameterised:
f(i, sum)
{
if(i < 1)
{
print(sum)
return;
}
f(i-1, sum+i)
}
main()
{
input n;
f(n, 0);
}
b) Functional:
f(n)
{
if(n == 0)
return 0;
return n + f(n-1);
}
main()
{
input(n)
print(f(n));
}
8) factorial of n:
f(n)
{
if(n == 1)
return 0;
return n * f(n-1);
}
main()
{
input(n)
print(f(n));
}
9) Reverse an array:
a)
f(l, r)
{ if(l >= r) return:
swap(a[l], a[r]);
f(l+1, r-1);
}
main()
{
input(array);
f(0, n-1);
}
b)
f(i)
{
if (i >= n/2)
return;
swap(a[i], a[n-i-1]);
f(i+1);
}
main()
{
input(array)
f(0);
}
10) check if string is palindrome:
f(i)
{
if (i >= n/2) return true;
if (s[i] != s[n-i-1])
return false;
return f(i+1);
}
main()
{
print(f(0))
}
11) Mutiple recursion calls:
a) fib numbers:
f(n)
{
if (n <= 1)
return n;
return f(n-1) + f(n-2);
}
main()
{
input(n);
print(f(n));
}
12) Print all subsequances (a contigous/ non-contigous sequence which follows the order)
f(i, [])
{
if (i >= n)
print([]);
return;
[].add (arr[i]);
f(i+1, [])
[].remove (arr[i]);
f(i+1, []);
}
main()
{
input(arr);
f(0, [])
}
13) Printing subsequances whose sum is K:
a)
f(i, [], s)
{
if(i == n)
{
if (s==sum)
print(ds);
return;
}
ds.add (arr[i]);
s+=arr[i];
f(i+1, ds, s);
ds.remove (arr[i]);
s-=arr[i];
f(i+1, ds, s);
}
b) print subsequance whose sum is sum:
f()
{ base case
if condition is satisfied
return True
if condition is Not satisfied return False
if (f() == true)
return true;
f()
return false;
}
c) count the subsequance with sum =k:
f()
{
base case
return 1 --> condition satisfied
return 0 --> condtion not satisfied
l = f()
r = f()
return l+r;
}
Download