Recursion
| 698 |
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 be the list of all possible full binary trees with nodes.
Every full binary tree 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 , we can formulate the recursion: [All trees with left child from and right child from , for all ].
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 so that we don't have to recalculate them in our recursion.
Comments
Post a Comment