96. Unique Binary Search Trees 等题

本文探讨了如何使用动态规划解决两种经典问题:构造不同形态的二叉搜索树及判断数组是否能分为两个和相等的子集。通过深入分析题目背后的数学原理,给出简洁高效的算法实现。

96. Unique Binary Search Trees

原题:

Given n, how many structurally unique BST’s (binary search trees) that store values 1…n?

For example,
Given n = 3, there are a total of 5 unique BST’s.

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

题解:
给定一个正整数n,问数字1~n可以构成多少棵不同的二叉搜索树。
首先要知道二叉搜索树的特性,就是每个节点的左子树中的所有元素都比它小,右子树中的节点都比它大。而且两个子树都是二叉搜索树。那么可以这样说。在1~n数字中,如果数字i作为根节点,那么根节点的左子树一定是由1 ~ i-1构成,右子树一定是i+1 ~ n。在这种情况下,i+1 ~ n中的数字可以整体减去i,变成1 ~ n-i的情况。很明显就是DP的状态转移了。
因此用f(n)表示n个数字有多少种不同的二叉搜索树,有:

# python表示
f(0) = f(1) = 1
f(n) = sum([f(i-1)*f(n-i) for i in range(1, n+1)])

代码:

class Solution {
public:
    int numTrees(int n) {
        if(n<2) {
            return 1;
        }
        vector<int> f(n+1);
        f[0] = 1;
        f[1] = 1;
        for(int i=1; i<=n; i++) {
            f[i] = 0;
            for(int j=1; j<=i; j++) {
                f[i] += f[j-1] * f[i-j];
            }
        }
        return f[n];
    }
};

416. Partition Equal Subset Sum

原题:
Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.

Note:
Each of the array element will not exceed 100.
The array size will not exceed 200.

Example 1:

Input: [1, 5, 11, 5]

Output: true

Explanation: The array can be partitioned as [1, 5, 5] and [11].

Example 2:

Input: [1, 2, 3, 5]

Output: false

Explanation: The array cannot be partitioned into equal sum subsets.

题解:
给一组正整数,问能否把它们分成两个子集,使得两个集合的和相等。

首先可以排除一个明显无解的情况:数组的和为奇数。

把数组和除于二后,得到一个subsum,于是把问题变成了subset sum问题。

subset sum问题有伪多项式的解法,用f(i, j)表示0到i个元素能否找到子集的和为j。

状态转移式为:

f(i, j) = (i == j) || (f(i-1, j)) || (j-i>=0 && f(i-1, j-i))

代码:

class Solution {
public:
    bool canPartition(vector<int>& nums) {
        int sum = 0;
        for(auto x: nums) {
            sum += x;
        }
        if(sum % 2) {
            return false;
        }

        sum /= 2;
        vector<vector<bool>> f(nums.size(), vector<bool>(sum+1));
        // f[0][sum] = (nums[0] == sum);
        for(int j=1; j<=sum; ++j) {
            f[0][j] = (nums[0] == j);
        }
        for(int i=1; i<nums.size(); ++i) {
            for(int j=1; j<=sum; ++j) {
                f[i][j] = (nums[i] == j) || (f[i-1][j]) || (j-nums[i]>=0 && f[i-1][j-nums[i]]);
            }
        }
        return f[nums.size()-1][sum];
    }
};
### 如何使用二叉搜索树(BST)实现 A+B 操作 在 C 编程语言中,可以通过构建两个二叉搜索树(BST),分别表示集合 A 和 B 的元素,然后通过遍历其中一个 BST 并将其节点插入到另一个 BST 中来完成 A+B 操作。以下是详细的实现方法: #### 数据结构定义 首先需要定义一个简单的二叉搜索树节点的数据结构。 ```c typedef struct TreeNode { int value; struct TreeNode* left; struct TreeNode* right; } TreeNode; ``` #### 插入函数 为了向 BST 添加新元素,可以编写如下 `insert` 函数。 ```c TreeNode* createNode(int value) { TreeNode* newNode = (TreeNode*)malloc(sizeof(TreeNode)); newNode->value = value; newNode->left = NULL; newNode->right = NULL; return newNode; } void insert(TreeNode** root, int value) { if (*root == NULL) { *root = createNode(value); } else { if (value < (*root)->value) { insert(&((*root)->left), value); // Insert into the left subtree. } else if (value > (*root)->value) { insert(&((*root)->right), value); // Insert into the right subtree. } // If value == (*root)->value, do nothing since duplicates are not allowed in a set. } } ``` #### 合并操作 要执行 A+B 操作,即合并两棵 BST,可以从一棵树中提取所有元素并将它们逐个插入另一棵树中。 ```c // In-order traversal to extract elements from one tree and add them to another. void mergeTrees(TreeNode* sourceRoot, TreeNode** targetRoot) { if (sourceRoot != NULL) { mergeTrees(sourceRoot->left, targetRoot); // Traverse left subtree first. insert(targetRoot, sourceRoot->value); // Add current node's value to target tree. mergeTrees(sourceRoot->right, targetRoot); // Then traverse right subtree. } } ``` #### 主程序逻辑 假设我们已经初始化了两棵 BST 表示集合 A 和 B,则可以通过调用上述函数完成 A+B 操作。 ```c int main() { TreeNode* treeA = NULL; TreeNode* treeB = NULL; // Example: Adding values to Tree A. int arrayA[] = {5, 3, 7, 2, 4}; for (size_t i = 0; i < sizeof(arrayA)/sizeof(arrayA[0]); ++i) { insert(&treeA, arrayA[i]); } // Example: Adding values to Tree B. int arrayB[] = {6, 8, 1}; for (size_t i = 0; i < sizeof(arrayB)/sizeof(arrayB[0]); ++i) { insert(&treeB, arrayB[i]); } // Perform A + B by merging all nodes of treeB into treeA. mergeTrees(treeB, &treeA); // Now treeA contains all unique elements from both sets. return 0; } ``` 此代码片段展示了如何利用二叉搜索树的性质高效地进行集合并集运算[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值