leetcode 95 96 不同的二叉搜尋樹
阿新 • • 發佈:2018-12-24
動態規劃刷題
1、leetcode96 不同的二叉搜尋樹
描述:給定一個整數 n,求以 1 ... n 為節點組成的二叉搜尋樹有多少種?
思路:
-
就是利用二叉樹的性質 根節點選定i之後 那麼它的左子樹的結點個數應該是 i -1;右子樹的結點的個數應該是 n-i;
-
它是個和的形式 因為它有i個分配方式;左右子樹的根節點數目不一樣 對應不同的情況;
那麼 它就應該累加起來;
那麼 遞推式子: f(x)+=f(x-1)*f(n-x)
class Solution { public: int numTrees(int n) { if(n==0) return 1; vector<int>dp(n+1,0); dp[0]=1;//注意dp[0]=1;也是一種方案; dp[1]=1; for(int i=2;i<=n;i++) for(int j=0;j<=i;j++) dp[i]=dp[j-1]*dp[i-j]; return dp[n]; } };
2、leetcode 95 不同二叉搜尋樹的輸出
##### 思路:
-
一個二叉樹的構造 從起始位置到終止位置進行構造;
設定一個輔助函式 從vector<TreeNode *>helper(int start,int end);來表示從start到end來構造二叉樹結果放在容器中;
-
index從start 到end進行遍歷;每一次結果壓入result中
-
然後當前結點的左子樹的結合 和右子樹的集合
-
從集合中不斷的取出一對左右子節點 (雙層迴圈)來構造出一個二叉搜尋樹;
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { private: vector<TreeNode *>result; vector<TreeNode*> helper(int start,int end) { vector<TreeNode *>res; if(start==end) res.push_back(new TreeNode(start)); else if(start>end) res.push_back(nullptr); else { for(int index=start;index<=end;index++) { vector<TreeNode *>left_union=helper(start,index-1);//構建左子樹的集合 vector<TreeNode *>right_union=helper(index+1,end);//構建右子樹的集合; for(int i=0;i<left_union.size();i++)//雙層迴圈遍歷 找出不同的左右子樹進行匹配構建的二叉搜尋樹; for(int j=0;j<right_union.size();j++) { TreeNode *root=new TreeNode(index); root->left=left_union[i]; root->right=right_union[j]; res.push_back(root); } } } return res; } public: vector<TreeNode*> generateTrees(int n) { if(n==0) return result; return helper(1,n); } };