diff --git a/backtracking/generate_all_parentheses_II/Cpp/generate_all_parentheses_II b/backtracking/generate_all_parentheses_II/Cpp/generate_all_parentheses_II new file mode 100755 index 0000000000..7898a66367 Binary files /dev/null and b/backtracking/generate_all_parentheses_II/Cpp/generate_all_parentheses_II differ diff --git a/backtracking/generate_all_parentheses_II/Cpp/generate_all_parentheses_II.cpp b/backtracking/generate_all_parentheses_II/Cpp/generate_all_parentheses_II.cpp new file mode 100644 index 0000000000..3c37cb1562 --- /dev/null +++ b/backtracking/generate_all_parentheses_II/Cpp/generate_all_parentheses_II.cpp @@ -0,0 +1,52 @@ +#include +using namespace std; + +void call (vector& ans, string st, int A, int cur){ + + if(cur==0 && A==0){ + ans.push_back(st); + return ; + } + + if(cur==0){ + st+='('; + call(ans,st,A-1,1); + return ; + } + + if(A){ + call(ans,st+'(',A-1,cur+1); + call(ans,st+')',A,cur-1); + return ; + } + + while(cur){ + st= st+')'; + cur--; + } + + ans.push_back(st); + return ; +} + +vector generateParenthesis(int A) { + + vector ans; + string st; + call(ans, st, A, 0); + return ans; +} + +int main() +{ + cout<<"Enter the number: "; + + int n; + cin>>n; + + vector ans=generateParenthesis(n); + + for(int i=0;i ans = generateParanthesis(n); + for (String an : ans) { + System.out.println(an); + } + } + + private static ArrayList generateParanthesis(int n){ + char[] str = new char[n*2]; + ArrayList list = new ArrayList<>(); + addParen(list, n, n, str, 0); + return list; + } + + private static void addParen(ArrayList list, int leftRem, int rightRem, char[] str, int index) { + + if(leftRem < 0 || rightRem < leftRem) //Invalid State + return; + + if(leftRem == 0 && rightRem == 0) //Out of left and right parenthesis + list.add(String.copyValueOf(str)); + + else{ + str[index] = '('; //Add left Parenthesis and recurse + addParen(list, leftRem-1, rightRem, str, index+1); + + str[index] = ')'; //Add right Parenthesis and recurse + addParen(list, leftRem, rightRem-1, str, index+1); + } + } +} + diff --git a/backtracking/generate_all_parentheses_II/c++/generate_all_parentheses_II.cpp b/backtracking/generate_all_parentheses_II/c++/generate_all_parentheses_II.cpp deleted file mode 100644 index 2594bde2ff..0000000000 --- a/backtracking/generate_all_parentheses_II/c++/generate_all_parentheses_II.cpp +++ /dev/null @@ -1,44 +0,0 @@ -#include -using namespace std; -void call (vector& ans, string st, int A,int cur){ - - if(cur==0&&A==0){ - ans.push_back(st); - return ; - } - if(cur==0){ - st+='('; - call(ans,st,A-1,1); - return ; - } - if(A){ - call(ans,st+'(',A-1,cur+1); - call(ans,st+')',A,cur-1); - return ; - } - while(cur){ - st= st+')'; - cur--; - } - ans.push_back(st); - return ; - -} -vector generateParenthesis(int A) { - -vector ans; -string st; -call(ans, st, A,0); - return ans; -} -int main() -{ - cout<<"Enter the number: "; - int n; - cin>>n; -vector ans=generateParenthesis(n); - -for(int i=0;i= 0 && x < N && y >= 0 && + y < N && sol[x][y] == -1); + } + + /* A utility function to print solution + matrix sol[N][N] */ + static void printSolution(int sol[][]) { + for (int x = 0; x < N; x++) { + for (int y = 0; y < N; y++) + System.out.print(sol[x][y] + " "); + System.out.println(); + } + } + + /* This function solves the Knight Tour problem + using Backtracking. This function mainly + uses solveKTUtil() to solve the problem. It + returns false if no complete tour is possible, + otherwise return true and prints the tour. + Please note that there may be more than one + solutions, this function prints one of the + feasible solutions. */ + static boolean solveKT() { + int sol[][] = new int[8][8]; + + /* Initialization of solution matrix */ + for (int x = 0; x < N; x++) + for (int y = 0; y < N; y++) + sol[x][y] = -1; + + /* xMove[] and yMove[] define next move of Knight. + xMove[] is for next value of x coordinate + yMove[] is for next value of y coordinate */ + int xMove[] = {2, 1, -1, -2, -2, -1, 1, 2}; + int yMove[] = {1, 2, 2, 1, -1, -2, -2, -1}; + + // Since the Knight is initially at the first block + sol[0][0] = 0; + + /* Start from 0,0 and explore all tours using + solveKTUtil() */ + if (!solveKTUtil(0, 0, 1, sol, xMove, yMove)) { + System.out.println("Solution does not exist"); + return false; + } else + printSolution(sol); + + return true; + } + + /* A recursive utility function to solve Knight + Tour problem */ + static boolean solveKTUtil(int x, int y, int movei, + int sol[][], int xMove[], + int yMove[]) { + int k, next_x, next_y; + if (movei == N * N) + return true; + + /* Try all next moves from the current coordinate + x, y */ + for (k = 0; k < 8; k++) { + next_x = x + xMove[k]; + next_y = y + yMove[k]; + if (isSafe(next_x, next_y, sol)) { + sol[next_x][next_y] = movei; + if (solveKTUtil(next_x, next_y, movei + 1, + sol, xMove, yMove)) + return true; + else + sol[next_x][next_y] = -1;// backtracking + } + } + + return false; + } + + /* Driver program to test above functions */ + public static void main(String args[]) { + solveKT(); + } +} + diff --git a/backtracking/m-coloring/Java/mColoringProblem.java b/backtracking/m-coloring/Java/mColoringProblem.java new file mode 100644 index 0000000000..caa5eaa69d --- /dev/null +++ b/backtracking/m-coloring/Java/mColoringProblem.java @@ -0,0 +1,114 @@ + +public class mColoringProblem { + final int V = 4; + int color[]; + + /* A utility function to check if the current + color assignment is safe for vertex v */ + boolean isSafe(int v, int graph[][], int color[], + int c) + { + for (int i = 0; i < V; i++) + if (graph[v][i] == 1 && c == color[i]) + return false; + return true; + } + + /* A recursive utility function to solve m + coloring problem */ + boolean graphColoringUtil(int graph[][], int m, + int color[], int v) + { + /* base case: If all vertices are assigned + a color then return true */ + if (v == V) + return true; + + /* Consider this vertex v and try different + colors */ + for (int c = 1; c <= m; c++) + { + /* Check if assignment of color c to v + is fine*/ + if (isSafe(v, graph, color, c)) + { + color[v] = c; + + /* recur to assign colors to rest + of the vertices */ + if (graphColoringUtil(graph, m, + color, v + 1)) + return true; + + /* If assigning color c doesn't lead + to a solution then remove it */ + color[v] = 0; + } + } + + /* If no color can be assigned to this vertex + then return false */ + return false; + } + + /* This function solves the m Coloring problem using + Backtracking. It mainly uses graphColoringUtil() + to solve the problem. It returns false if the m + colors cannot be assigned, otherwise return true + and prints assignments of colors to all vertices. + Please note that there may be more than one + solutions, this function prints one of the + feasible solutions.*/ + boolean graphColoring(int graph[][], int m) + { + // Initialize all color values as 0. This + // initialization is needed correct functioning + // of isSafe() + color = new int[V]; + for (int i = 0; i < V; i++) + color[i] = 0; + + // Call graphColoringUtil() for vertex 0 + if (!graphColoringUtil(graph, m, color, 0)) + { + System.out.println("Solution does not exist"); + return false; + } + + // Print the solution + printSolution(color); + return true; + } + + /* A utility function to print solution */ + void printSolution(int color[]) + { + System.out.println("Solution Exists: Following" + + " are the assigned colors"); + for (int i = 0; i < V; i++) + System.out.print(" " + color[i] + " "); + System.out.println(); + } + + // driver program to test above function + public static void main(String args[]) + { + mColoringProblem Coloring = new mColoringProblem(); + /* Create following graph and test whether it is + 3 colorable + (3)---(2) + | / | + | / | + | / | + (0)---(1) + */ + int graph[][] = {{0, 1, 1, 1}, + {1, 0, 1, 0}, + {1, 1, 0, 1}, + {1, 0, 1, 0}, + }; + int m = 3; // Number of colors + Coloring.graphColoring(graph, m); + } +} + diff --git a/backtracking/m-coloring/Python/mColoring.py b/backtracking/m-coloring/Python/mColoring.py new file mode 100644 index 0000000000..648e6e1976 --- /dev/null +++ b/backtracking/m-coloring/Python/mColoring.py @@ -0,0 +1,48 @@ + + +class Graph(): + + def __init__(self, vertices): + self.V = vertices + self.graph = [[0 for column in range(vertices)]\ + for row in range(vertices)] + + # A utility function to check if the current color assignment + # is safe for vertex v + def isSafe(self, v, colour, c): + for i in range(self.V): + if self.graph[v][i] == 1 and colour[i] == c: + return False + return True + + # A recursive utility function to solve m + # coloring problem + def graphColourUtil(self, m, colour, v): + if v == self.V: + return True + + for c in range(1, m+1): + if self.isSafe(v, colour, c) == True: + colour[v] = c + if self.graphColourUtil(m, colour, v+1) == True: + return True + colour[v] = 0 + + def graphColouring(self, m): + colour = [0] * self.V + if self.graphColourUtil(m, colour, 0) == False: + return False + + # Print the solution + print "Solution exist and Following are the assigned colours:" + for c in colour: + print c, + return True + +# Driver Code +g = Graph(4) +g.graph = [[0,1,1,1], [1,0,1,0], [1,1,0,1], [1,0,1,0]] +m=3 +g.graphColouring(m) + + diff --git a/dp/EditDistance/Java/EDIST.java b/dp/EditDistance/Java/EDIST.java new file mode 100644 index 0000000000..a9dea8d2b8 --- /dev/null +++ b/dp/EditDistance/Java/EDIST.java @@ -0,0 +1,45 @@ + +class EDIST +{ + static int min(int x,int y,int z) + { + if (x<=y && x<=z) return x; + if (y<=x && y<=z) return y; + else return z; + } + + static int editDist(String str1 , String str2 , int m ,int n) + { + // If first string is empty, the only option is to + // insert all characters of second string into first + if (m == 0) return n; + + // If second string is empty, the only option is to + // remove all characters of first string + if (n == 0) return m; + + // If last characters of two strings are same, nothing + // much to do. Ignore last characters and get count for + // remaining strings. + if (str1.charAt(m-1) == str2.charAt(n-1)) + return editDist(str1, str2, m-1, n-1); + + // If last characters are not same, consider all three + // operations on last character of first string, recursively + // compute minimum cost for all three operations and take + // minimum of three values. + return 1 + min ( editDist(str1, str2, m, n-1), // Insert + editDist(str1, str2, m-1, n), // Remove + editDist(str1, str2, m-1, n-1) // Replace + ); + } + + public static void main(String args[]) + { + String str1 = "sunday"; + String str2 = "saturday"; + + System.out.println( editDist( str1 , str2 , str1.length(), str2.length()) ); + } +} + diff --git a/dp/EditDistance/Python/EditDistance.py b/dp/EditDistance/Python/EditDistance.py new file mode 100644 index 0000000000..af4bc57786 --- /dev/null +++ b/dp/EditDistance/Python/EditDistance.py @@ -0,0 +1,34 @@ + +def editDistance(str1, str2, m , n): + + # If first string is empty, the only option is to + # insert all characters of second string into first + if m==0: + return n + + # If second string is empty, the only option is to + # remove all characters of first string + if n==0: + return m + + # If last characters of two strings are same, nothing + # much to do. Ignore last characters and get count for + # remaining strings. + if str1[m-1]==str2[n-1]: + return editDistance(str1,str2,m-1,n-1) + + # If last characters are not same, consider all three + # operations on last character of first string, recursively + # compute minimum cost for all three operations and take + # minimum of three values. + return 1 + min(editDistance(str1, str2, m, n-1), # Insert + editDistance(str1, str2, m-1, n), # Remove + editDistance(str1, str2, m-1, n-1) # Replace + ) + +# Driver program to test the above function +str1 = "sunday" +str2 = "saturday" +print editDistance(str1, str2, len(str1), len(str2)) + + diff --git a/dp/Lowest_Common_Ancestor/Java/LCA.java b/dp/Lowest_Common_Ancestor/Java/LCA.java new file mode 100644 index 0000000000..3081b77442 --- /dev/null +++ b/dp/Lowest_Common_Ancestor/Java/LCA.java @@ -0,0 +1,91 @@ +import java.util.ArrayList; +import java.util.List; + +class Node { + int data; + Node left, right; + + Node(int value) { + data = value; + left = right = null; + } +} + +public class BT_NoParentPtr_Solution1 +{ + + Node root; + private List path1 = new ArrayList<>(); + private List path2 = new ArrayList<>(); + + int findLCA(int n1, int n2) { + path1.clear(); + path2.clear(); + return findLCAInternal(root, n1, n2); + } + + private int findLCAInternal(Node root, int n1, int n2) { + + if (!findPath(root, n1, path1) || !findPath(root, n2, path2)) { + System.out.println((path1.size() > 0) ? "n1 is present" : "n1 is missing"); + System.out.println((path2.size() > 0) ? "n2 is present" : "n2 is missing"); + return -1; + } + + int i; + for (i = 0; i < path1.size() && i < path2.size(); i++) { + // System.out.println(path1.get(i) + " " + path2.get(i)); + if (!path1.get(i).equals(path2.get(i))) + break; + } + + return path1.get(i-1); + } + + private boolean findPath(Node root, int n, List path) + { + if (root == null) { + return false; + } + + path.add(root.data); + + if (root.data == n) { + return true; + } + + if (root.left != null && findPath(root.left, n, path)) { + return true; + } + + if (root.right != null && findPath(root.right, n, path)) { + return true; + } + + path.remove(path.size()-1); + + return false; + } + + public static void main(String[] args) + { + BT_NoParentPtr_Solution1 tree = new BT_NoParentPtr_Solution1(); + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + tree.root.right.left = new Node(6); + tree.root.right.right = new Node(7); + + System.out.println("LCA(4, 5): " + tree.findLCA(4,5)); + System.out.println("LCA(4, 6): " + tree.findLCA(4,6)); + System.out.println("LCA(3, 4): " + tree.findLCA(3,4)); + System.out.println("LCA(2, 4): " + tree.findLCA(2,4)); + /* System.out.println("LCA(4, 7): " + tree.findLCA(4,7)); + System.out.println("LCA(4, 8): " + tree.findLCA(4,8)); + System.out.println("LCA(1, 1): " + tree.findLCA(1,1)); */ + } +} +// This code is contributed by Sreenivasulu Rayanki. + diff --git a/dp/Lowest_Common_Ancestor/Python/lcs.py b/dp/Lowest_Common_Ancestor/Python/lcs.py new file mode 100644 index 0000000000..998fff8da7 --- /dev/null +++ b/dp/Lowest_Common_Ancestor/Python/lcs.py @@ -0,0 +1,72 @@ + +class Node: + # Constructor to create a new binary node + def __init__(self, key): + self.key = key + self.left = None + self.right = None + +# Finds the path from root node to given root of the tree. +# Stores the path in a list path[], returns true if path +# exists otherwise false +def findPath( root, path, k): + + # Baes Case + if root is None: + return False + + # Store this node is path vector. The node will be + # removed if not in path from root to k + path.append(root.key) + + # See if the k is same as root's key + if root.key == k : + return True + + # Check if k is found in left or right sub-tree + if ((root.left != None and findPath(root.left, path, k)) or + (root.right!= None and findPath(root.right, path, k))): + return True + + # If not present in subtree rooted with root, remove + # root from path and return False + + path.pop() + return False + +# Returns LCA if node n1 , n2 are present in the given +# binary tre otherwise return -1 +def findLCA(root, n1, n2): + + # To store paths to n1 and n2 fromthe root + path1 = [] + path2 = [] + + # Find paths from root to n1 and root to n2. + # If either n1 or n2 is not present , return -1 + if (not findPath(root, path1, n1) or not findPath(root, path2, n2)): + return -1 + + # Compare the paths to get the first different value + i = 0 + while(i < len(path1) and i < len(path2)): + if path1[i] != path2[i]: + break + i += 1 + return path1[i-1] + + +# Driver program to test above function +# Let's create the Binary Tree shown in above diagram +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) +root.right.left = Node(6) +root.right.right = Node(7) + +print "LCA(4, 5) = %d" %(findLCA(root, 4, 5,)) +print "LCA(4, 6) = %d" %(findLCA(root, 4, 6)) +print "LCA(3, 4) = %d" %(findLCA(root,3,4)) +print "LCA(2, 4) = %d" %(findLCA(root,2, 4)) diff --git a/dp/egg_dropping_puzzle/Java/eggDropping.java b/dp/egg_dropping_puzzle/Java/eggDropping.java new file mode 100644 index 0000000000..ec54aa45a9 --- /dev/null +++ b/dp/egg_dropping_puzzle/Java/eggDropping.java @@ -0,0 +1,58 @@ + +class EggDrop +{ + // A utility function to get maximum of two integers + static int max(int a, int b) { return (a > b)? a: b; } + + /* Function to get minimum number of trials needed in worst + case with n eggs and k floors */ + static int eggDrop(int n, int k) + { + /* A 2D table where entery eggFloor[i][j] will represent minimum + number of trials needed for i eggs and j floors. */ + int eggFloor[][] = new int[n+1][k+1]; + int res; + int i, j, x; + + // We need one trial for one floor and0 trials for 0 floors + for (i = 1; i <= n; i++) + { + eggFloor[i][1] = 1; + eggFloor[i][0] = 0; + } + + // We always need j trials for one egg and j floors. + for (j = 1; j <= k; j++) + eggFloor[1][j] = j; + + // Fill rest of the entries in table using optimal substructure + // property + for (i = 2; i <= n; i++) + { + for (j = 2; j <= k; j++) + { + eggFloor[i][j] = Integer.MAX_VALUE; + for (x = 1; x <= j; x++) + { + res = 1 + max(eggFloor[i-1][x-1], eggFloor[i][j-x]); + if (res < eggFloor[i][j]) + eggFloor[i][j] = res; + } + } + } + + // eggFloor[n][k] holds the result + return eggFloor[n][k]; + + } + + /* Driver program to test to pront printDups*/ + public static void main(String args[] ) + { + int n = 2, k = 10; + System.out.println("Minimum number of trials in worst case with "+n+" eggs and "+k+ + " floors is "+eggDrop(n, k)); + } +} + + diff --git a/dp/egg_dropping_puzzle/Python/EggDropping.py b/dp/egg_dropping_puzzle/Python/EggDropping.py new file mode 100644 index 0000000000..64b1bf1042 --- /dev/null +++ b/dp/egg_dropping_puzzle/Python/EggDropping.py @@ -0,0 +1,39 @@ + +INT_MAX = 32767 + +# Function to get minimum number of trials needed in worst +# case with n eggs and k floors +def eggDrop(n, k): + # A 2D table where entery eggFloor[i][j] will represent minimum + # number of trials needed for i eggs and j floors. + eggFloor = [[0 for x in range(k+1)] for x in range(n+1)] + + # We need one trial for one floor and0 trials for 0 floors + for i in range(1, n+1): + eggFloor[i][1] = 1 + eggFloor[i][0] = 0 + + # We always need j trials for one egg and j floors. + for j in range(1, k+1): + eggFloor[1][j] = j + + # Fill rest of the entries in table using optimal substructure + # property + for i in range(2, n+1): + for j in range(2, k+1): + eggFloor[i][j] = INT_MAX + for x in range(1, j+1): + res = 1 + max(eggFloor[i-1][x-1], eggFloor[i][j-x]) + if res < eggFloor[i][j]: + eggFloor[i][j] = res + + # eggFloor[n][k] holds the result + return eggFloor[n][k] + +# Driver program to test to pront printDups +n = 2 +k = 36 +print("Minimum number of trials in worst case with" + str(n) + "eggs and " + + str(k) + " floors is " + str(eggDrop(n, k))) + + diff --git a/dp/kadane-_algorithm/Java/kadane.java b/dp/kadane-_algorithm/Java/kadane.java new file mode 100644 index 0000000000..1aa8eb343f --- /dev/null +++ b/dp/kadane-_algorithm/Java/kadane.java @@ -0,0 +1,30 @@ +import java.io.*; + +import java.util.*; + +class kadane +{ + public static void main (String[] args) + { + int [] a = {-2, -3, 4, -1, -2, 1, 5, -3}; + System.out.println("Maximum contiguous sum is " + + maxSubArraySum(a)); + } + + static int maxSubArraySum(int a[]) + { + int size = a.length; + int max_so_far = Integer.MIN_VALUE, max_ending_here = 0; + + for (int i = 0; i < size; i++) + { + max_ending_here = max_ending_here + a[i]; + if (max_so_far < max_ending_here) + max_so_far = max_ending_here; + if (max_ending_here < 0) + max_ending_here = 0; + } + return max_so_far; + } +} + diff --git a/dp/longest_common_subsequence/Java/LongestCommonSubsequence.java b/dp/longest_common_subsequence/Java/LongestCommonSubsequence.java new file mode 100644 index 0000000000..1861fe282a --- /dev/null +++ b/dp/longest_common_subsequence/Java/LongestCommonSubsequence.java @@ -0,0 +1,39 @@ + +public class LongestCommonSubsequence +{ + +/* Returns length of LCS for X[0..m-1], Y[0..n-1] */ +int lcs( char[] X, char[] Y, int m, int n ) +{ + if (m == 0 || n == 0) + return 0; + if (X[m-1] == Y[n-1]) + return 1 + lcs(X, Y, m-1, n-1); + else + return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n)); +} + +/* Utility function to get max of 2 integers */ +int max(int a, int b) +{ + return (a > b)? a : b; +} + +public static void main(String[] args) +{ + LongestCommonSubsequence lcs = new LongestCommonSubsequence(); + String s1 = "AGGTAB"; + String s2 = "GXTXAYB"; + + char[] X=s1.toCharArray(); + char[] Y=s2.toCharArray(); + int m = X.length; + int n = Y.length; + + System.out.println("Length of LCS is" + " " + + lcs.lcs( X, Y, m, n ) ); +} + +} + + diff --git a/dp/longest_palidromic_subsequence/Java/LongestPalindromicSubsequence.java b/dp/longest_palidromic_subsequence/Java/LongestPalindromicSubsequence.java new file mode 100644 index 0000000000..9b41f2a8e5 --- /dev/null +++ b/dp/longest_palidromic_subsequence/Java/LongestPalindromicSubsequence.java @@ -0,0 +1,46 @@ + +class LPS +{ + + // A utility function to get max of two integers + static int max (int x, int y) { return (x > y)? x : y; } + + // Returns the length of the longest palindromic subsequence in seq + static int lps(String seq) + { + int n = seq.length(); + int i, j, cl; + int L[][] = new int[n][n]; // Create a table to store results of subproblems + + // Strings of length 1 are palindrome of lentgh 1 + for (i = 0; i < n; i++) + L[i][i] = 1; + + + for (cl=2; cl<=n; cl++) + { + for (i=0; i +#include +using namespace std; + +// This function mainly returns LCS(str, str) +// with a condition that same characters at +// same index are not considered. +int findLongestRepeatingSubSeq(string str) +{ + int n = str.length(); + + // Create and initialize DP table + int dp[n+1][n+1]; + for (int i=0; i<=n; i++) + for (int j=0; j<=n; j++) + dp[i][j] = 0; + + // Fill dp table (similar to LCS loops) + for (int i=1; i<=n; i++) + { + for (int j=1; j<=n; j++) + { + // If characters match and indexes are + // not same + if (str[i-1] == str[j-1] && i != j) + dp[i][j] = 1 + dp[i-1][j-1]; + + // If characters do not match + else + dp[i][j] = max(dp[i][j-1], dp[i-1][j]); + } + } + return dp[n][n]; +} + +// Driver Program +int main() +{ + string str = "aabb"; + cout << "The length of the largest subsequence that" + " repeats itself is : " + << findLongestRepeatingSubSeq(str); + return 0; +} + diff --git a/dp/longest_repeating_subsequence/Java/LRS.java b/dp/longest_repeating_subsequence/Java/LRS.java new file mode 100644 index 0000000000..af1843e30f --- /dev/null +++ b/dp/longest_repeating_subsequence/Java/LRS.java @@ -0,0 +1,41 @@ + +import java.io.*; +import java.util.*; + +class LRS +{ + // Function to find the longest repeating subsequence + static int findLongestRepeatingSubSeq(String str) + { + int n = str.length(); + + // Create and initialize DP table + int[][] dp = new int[n+1][n+1]; + + // Fill dp table (similar to LCS loops) + for (int i=1; i<=n; i++) + { + for (int j=1; j<=n; j++) + { + // If characters match and indexes are not same + if (str.charAt(i-1) == str.charAt(j-1) && i!=j) + dp[i][j] = 1 + dp[i-1][j-1]; + + // If characters do not match + else + dp[i][j] = Math.max(dp[i][j-1], dp[i-1][j]); + } + } + return dp[n][n]; + } + + // driver program to check above function + public static void main (String[] args) + { + String str = "aabb"; + System.out.println("The length of the largest subsequence that" + +" repeats itself is : "+findLongestRepeatingSubSeq(str)); + } +} + + diff --git a/graph/Java/BFS.java b/graph/Java/BFS.java new file mode 100644 index 0000000000..1a9b664e1c --- /dev/null +++ b/graph/Java/BFS.java @@ -0,0 +1,81 @@ + +import java.io.*; +import java.util.*; + +// This class represents a directed graph using adjacency list +// representation +class Graph +{ + private int V; // No. of vertices + private LinkedList adj[]; //Adjacency Lists + + // Constructor + Graph(int v) + { + V = v; + adj = new LinkedList[v]; + for (int i=0; i queue = new LinkedList(); + + // Mark the current node as visited and enqueue it + visited[s]=true; + queue.add(s); + + while (queue.size() != 0) + { + // Dequeue a vertex from queue and print it + s = queue.poll(); + System.out.print(s+" "); + + // Get all adjacent vertices of the dequeued vertex s + // If a adjacent has not been visited, then mark it + // visited and enqueue it + Iterator i = adj[s].listIterator(); + while (i.hasNext()) + { + int n = i.next(); + if (!visited[n]) + { + visited[n] = true; + queue.add(n); + } + } + } + } + + // Driver method to + public static void main(String args[]) + { + Graph g = new Graph(4); + + g.addEdge(0, 1); + g.addEdge(0, 2); + g.addEdge(1, 2); + g.addEdge(2, 0); + g.addEdge(2, 3); + g.addEdge(3, 3); + + System.out.println("Following is Breadth First Traversal "+ + "(starting from vertex 2)"); + + g.BFS(2); + } +} + diff --git a/graph/Java/DFS.java b/graph/Java/DFS.java new file mode 100644 index 0000000000..9a756679f2 --- /dev/null +++ b/graph/Java/DFS.java @@ -0,0 +1,74 @@ + +import java.io.*; +import java.util.*; + +// This class represents a directed graph using adjacency list +// representation +class Graph +{ + private int V; // No. of vertices + + // Array of lists for Adjacency List Representation + private LinkedList adj[]; + + // Constructor + Graph(int v) + { + V = v; + adj = new LinkedList[v]; + for (int i=0; i i = adj[v].listIterator(); + while (i.hasNext()) + { + int n = i.next(); + if (!visited[n]) + DFSUtil(n, visited); + } + } + + // The function to do DFS traversal. It uses recursive DFSUtil() + void DFS(int v) + { + // Mark all the vertices as not visited(set as + // false by default in java) + boolean visited[] = new boolean[V]; + + // Call the recursive helper function to print DFS traversal + DFSUtil(v, visited); + } + + public static void main(String args[]) + { + Graph g = new Graph(4); + + g.addEdge(0, 1); + g.addEdge(0, 2); + g.addEdge(1, 2); + g.addEdge(2, 0); + g.addEdge(2, 3); + g.addEdge(3, 3); + + System.out.println("Following is Depth First Traversal "+ + "(starting from vertex 2)"); + + g.DFS(2); + } +} + diff --git a/graph/Python/BFS.py b/graph/Python/BFS.py new file mode 100644 index 0000000000..bdc3775d87 --- /dev/null +++ b/graph/Python/BFS.py @@ -0,0 +1,60 @@ + +from collections import defaultdict + +# This class represents a directed graph using adjacency +# list representation +class Graph: + + # Constructor + def __init__(self): + + # default dictionary to store graph + self.graph = defaultdict(list) + + # function to add an edge to graph + def addEdge(self,u,v): + self.graph[u].append(v) + + # Function to print a BFS of graph + def BFS(self, s): + + # Mark all the vertices as not visited + visited = [False]*(len(self.graph)) + + # Create a queue for BFS + queue = [] + + # Mark the source node as visited and enqueue it + queue.append(s) + visited[s] = True + + while queue: + + # Dequeue a vertex from queue and print it + s = queue.pop(0) + print s, + + # Get all adjacent vertices of the dequeued + # vertex s. If a adjacent has not been visited, + # then mark it visited and enqueue it + for i in self.graph[s]: + if visited[i] == False: + queue.append(i) + visited[i] = True + + +# Driver code +# Create a graph given in the above diagram +g = Graph() +g.addEdge(0, 1) +g.addEdge(0, 2) +g.addEdge(1, 2) +g.addEdge(2, 0) +g.addEdge(2, 3) +g.addEdge(3, 3) + +print "Following is Breadth First Traversal (starting from vertex 2)" +g.BFS(2) + + + diff --git a/graph/Python/DFS.py b/graph/Python/DFS.py new file mode 100644 index 0000000000..beeaec7f6d --- /dev/null +++ b/graph/Python/DFS.py @@ -0,0 +1,56 @@ + +from collections import defaultdict + +# This class represents a directed graph using +# adjacency list representation +class Graph: + + # Constructor + def __init__(self): + + # default dictionary to store graph + self.graph = defaultdict(list) + + # function to add an edge to graph + def addEdge(self,u,v): + self.graph[u].append(v) + + # A function used by DFS + def DFSUtil(self,v,visited): + + # Mark the current node as visited and print it + visited[v]= True + print v, + + # Recur for all the vertices adjacent to this vertex + for i in self.graph[v]: + if visited[i] == False: + self.DFSUtil(i, visited) + + + # The function to do DFS traversal. It uses + # recursive DFSUtil() + def DFS(self,v): + + # Mark all the vertices as not visited + visited = [False]*(len(self.graph)) + + # Call the recursive helper function to print + # DFS traversal + self.DFSUtil(v,visited) + + +# Driver code +# Create a graph given in the above diagram +g = Graph() +g.addEdge(0, 1) +g.addEdge(0, 2) +g.addEdge(1, 2) +g.addEdge(2, 0) +g.addEdge(2, 3) +g.addEdge(3, 3) + +print "Following is DFS from (starting from vertex 2)" +g.DFS(2) + + diff --git a/greedy/huffman_coding/Java/HuffmanCoding.java b/greedy/huffman_coding/Java/HuffmanCoding.java new file mode 100644 index 0000000000..e2063a1465 --- /dev/null +++ b/greedy/huffman_coding/Java/HuffmanCoding.java @@ -0,0 +1,137 @@ +import java.util.PriorityQueue; +import java.util.Scanner; +import java.util.Comparator; + +// node class is the basic structure +// of each node present in the huffman - tree. +class HuffmanNode { + + int data; + char c; + + HuffmanNode left; + HuffmanNode right; +} + +// comparator class helps to compare the node +// on the basis of one of its attribute. +// Here we will be compared +// on the basis of data values of the nodes. +class MyComparator implements Comparator { + public int compare(HuffmanNode x, HuffmanNode y) + { + + return x.data - y.data; + } +} + +public class Huffman { + + // recursive function to print the + // huffman-code through the tree traversal. + // Here s is the huffman - code generated. + public static void printCode(HuffmanNode root, String s) + { + + // base case; if the left and right are null + // then its a leaf node and we print + // the code s generated by traversing the tree. + if (root.left + == null + && root.right + == null + && Character.isLetter(root.c)) { + + // c is the character in the node + System.out.println(root.c + ":" + s); + + return; + } + + // if we go to left then add "0" to the code. + // if we go to the right add"1" to the code. + + // recursive calls for left and + // right sub-tree of the generated tree. + printCode(root.left, s + "0"); + printCode(root.right, s + "1"); + } + + // main function + public static void main(String[] args) + { + + Scanner s = new Scanner(System.in); + + // number of characters. + int n = 6; + char[] charArray = { 'a', 'b', 'c', 'd', 'e', 'f' }; + int[] charfreq = { 5, 9, 12, 13, 16, 45 }; + + // creating a priority queue q. + // makes a min-priority queue(min-heap). + PriorityQueue q + = new PriorityQueue(n, new MyComparator()); + + for (int i = 0; i < n; i++) { + + // creating a huffman node object + // and adding it to the priority-queue. + HuffmanNode hn = new HuffmanNode(); + + hn.c = charArray[i]; + hn.data = charfreq[i]; + + hn.left = null; + hn.right = null; + + // add functions adds + // the huffman node to the queue. + q.add(hn); + } + + // create a root node + HuffmanNode root = null; + + // Here we will extract the two minimum value + // from the heap each time until + // its size reduces to 1, extract until + // all the nodes are extracted. + while (q.size() > 1) { + + // first min extract. + HuffmanNode x = q.peek(); + q.poll(); + + // second min extarct. + HuffmanNode y = q.peek(); + q.poll(); + + // new node f which is equal + HuffmanNode f = new HuffmanNode(); + + // to the sum of the frequency of the two nodes + // assigning values to the f node. + f.data = x.data + y.data; + f.c = '-'; + + // first extracted node as left child. + f.left = x; + + // second extracted node as the right child. + f.right = y; + + // marking the f node as the root node. + root = f; + + // add this node to the priority-queue. + q.add(f); + } + + // print the codes by traversing the tree + printCode(root, ""); + } +} + +// This code is contributed by Kunwar Desh Deepak Singh +