Recursion



698
  Note this is similar to DFS problem 473 Matchsticks to Square. The partition problem is NP-Complete.
 Base Case:
 if (k <= 0 ||  sum % k != 0) return false
Call  helper function: canPartition(nums, visited, 0, k, 0, sum / k);
bool canPartition(vector<int>& nums, vector<bool>& visited, int start_index, int k, int cur_sum, int target) {}
  Base case for helper:
        if (k == 1)
            return true;

  if (cur_sum == target)  recursively call the helper with decreased k value by 1
            return canPartition(nums, visited, 0 /*reset to 0*/, k - 1, 0, target);

 Otherwise, for loop each number in the array, if not visited, mark it as visited and recursively call the helper canPartition with updated cur_sum and cur_num and increased start_index value. if any partition succeeds, return true. Otherwise, unmark the current num in the flag array and try next number.



The longest univalue path is from one of the three cases:
(a)  longestUnivaluePath(root->left)
(b)  longestUnivaluePath(root->right)
(c)  the longest univalue path that use tree root->val (^ form)

Implementation:
        int leftLUP = longestUnivaluePath(root->left);
        int rightLUP = longestUnivaluePath(root->right);
        int leftDepth = univalueDepth(root->left, root->val);
        int rightDepth = univalueDepth(root->right, root->val);
        return max({leftLUP, rightLUP, leftDepth + rightDepth});

int univalueDepth(TreeNode* root, int val) {
        if (!root || root->val != val)
            return 0;
       
        return max(univalueDepth(root->left, val), univalueDepth(root->right, val)) + 1;
    }
    


894
Let \text{FBT}(N) be the list of all possible full binary trees with N nodes.
Every full binary tree T with 3 or more nodes, has 2 children at its root. Each of those children left and right are themselves full binary trees.
Thus, for N \geq 3, we can formulate the recursion: \text{FBT}(N) = [All trees with left child from \text{FBT}(x) and right child from \text{FBT}(N-1-x), for all x].
Also, by a simple counting argument, there are no full binary trees with a positive, even number of nodes.
Finally, we should cache previous results of the function \text{FBT} so that we don't have to recalculate them in our recursion.

Comments

Popular posts from this blog

zhitongguigu

Array Part2

Two pointers (Part 1)