forked from CodeSadhu/Hacktoberfest2020
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create kth symbol grammar leetcode problem.cpp
- Loading branch information
Showing
1 changed file
with
26 additions
and
0 deletions.
There are no files selected for viewing
26 changes: 26 additions & 0 deletions
26
C and C++/Competitive Problem Solutions/Leetcode/kth symbol grammar leetcode problem.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
//Overview of hypothesis developed in kth symbol in grammar: | ||
//The hypothesis of kth grammar function in designed such that the first half returns the same as N-1th row and second half in else condition gives the complement. | ||
//Remember recursion work like magic ,you don't have to think how it works, just have good observation skills and compute only till the second last step. | ||
//Eg: | ||
//Input: N = 4, K = 5 | ||
//Output: | ||
//N=1 0 | ||
//N=2 0 1 | ||
//N=3 0 1 1 0 | ||
//N=4 0 1 1 0 1 0 0 1 | ||
|
||
class Solution { | ||
public: | ||
int kthGrammar(int N, int K) { | ||
//base condition | ||
if(N==1||K==1) | ||
return 0; | ||
int mid=pow(2,N-1)/2; | ||
//hypothesis and induction | ||
if(K<=mid) | ||
return kthGrammar(N-1,K); | ||
else | ||
return !kthGrammar(N-1,K-mid); | ||
|
||
} | ||
}; |