Java Program to Find Size of the Largest Independent Set(LIS) in a Given an N-array Tree
Basically, an N-array tree is such a tree structure in which each node can have a max of up to ‘N’ number of children. The largest independent set is a set of vertices in which no two vertexes are adjacent to each other. So basically in this program, we have to see that how can we find the size of such a largest set in the N-array tree. Here we are implementing the tree using a vector in java and its idea of adjacency list from the graph theory is used.
The algorithm goes as:
What mainly we are going to do is that we will create a LIS(int a) method to which the number of the current node is passed. This is a recursive method. In this method, we will check the base conditions first. Before discussing the base conditions, we have to first see the rest part of the method.
So in the code, for each node, we mainly see that whether including that node inset gives the larger set or not. If not then that particular node is not included but since this node is not included, so we have to repeat the same process for its children. But if the node is included then we cannot include its children, so we have to check for its grandchildren the same thing ad done for the parent, and in this way we can get to know whether to include this node or not.
Now coming to the base cases:
- If the node is null, which means the node does not exist then we cannot include anything.
- If the node is a leaf then we must include it.
Why to always include those nodes which are leaf node, when method is called upon them?
The main part to think here is that some node may be passed to this method only if its parent are not included in the set except the root one. So if parents are not there in set and this node is leaf one then we should include this node in the set. This is basically a greedy approach.
We will also be making a small change in our code to print the set elements also.
Initializing an n array tree Finding the elements to be included in the set 6 4 6 5 4 6 5 0 process finished and size is 4
Since the output shows the elements of the set more than once, so we have to basically implement a map or a set datatype to get the elements uniquely.
Second thing to note is that this method is recursive approach so this can lead to exponential time complexity. This method can be enhanced using DP approach. We can achieve memorization through map data structure.
Please Login to comment...