Count number of paths whose weight is exactly X and has at-least one edge of weight M
Given an infinite tree and three numbers N, M, and X which has exactly N child from every node. Every edge has a weight of 1, 2, 3, 4..N. The task is to find the count of paths whose weight is exactly X and has a minimum of one edge of weight M in it.
The diagram above shows a tree shown till level-3 and N = 3.
Input: N = 3, M = 2, X = 3
The path 1-2 and 2-1 in the image above
Input: N = 2, M = 1, X = 4
Approach: The problem can be solved using Dynamic Programming and memoization. We will use a top-down approach to solve this problem. Recur starting from the root with sum initially as X, and recursively traverse all paths possible( which is from 1 to N). If the node is equal to M, then the second parameter becomes true, else it stays the same which has been passed in the previous call. Store the value in a DP table to avoid visiting same states twice.
Below is the implementation of the above approach.