File tree Expand file tree Collapse file tree 4 files changed +83
-0
lines changed
113.Path Sum II/coderfive
114.Flatten Binary Tree to Linked List/coderfive
115.Distinct Subsequences/coderfive Expand file tree Collapse file tree 4 files changed +83
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ bool hasPathSum (TreeNode* root, int sum) {
4
+ if (!root) return false ;
5
+ sum -= root->val ;
6
+ if (root->left && hasPathSum (root->left , sum)) return true ;
7
+ if (root->right && hasPathSum (root->right , sum)) return true ;
8
+ if (!root->left && !root->right && sum == 0 ) return true ;
9
+ return false ;
10
+ }
11
+ };
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ vector<vector<int >> pathSum (TreeNode* root, int sum) {
4
+ vector<vector<int >> res;
5
+ vector<int > v;
6
+ helper (root, res, v, sum);
7
+ return res;
8
+ }
9
+ void helper (TreeNode* root, vector<vector<int >>& res, vector<int >& path, int sum) {
10
+ if (!root) return ;
11
+ path.push_back (root->val );
12
+ sum -= root->val ;
13
+ if (!root->left && !root->right && sum == 0 )
14
+ res.push_back (path);
15
+ helper (root->left , res, path, sum);
16
+ helper (root->right , res, path, sum);
17
+
18
+ path.pop_back ();
19
+ }
20
+ };
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ void flatten (TreeNode* root) {
4
+ if (!root) return ;
5
+ helper (root);
6
+ }
7
+ TreeNode* helper (TreeNode* root) {
8
+ TreeNode* cur = root, *right = root->right ;
9
+ if (root->left ) {
10
+ root->right = root->left ;
11
+ cur = helper (root->left );
12
+ root->left = NULL ;
13
+ }
14
+ if (right) {
15
+ cur->right = right;
16
+ cur = helper (right);
17
+ }
18
+ return cur;
19
+ }
20
+ };
Original file line number Diff line number Diff line change
1
+ #include < map>
2
+ #include < vector>
3
+ #include < string>
4
+ #include < iostream>
5
+ using namespace std ;
6
+
7
+ class Solution {
8
+ public:
9
+ int numDistinct (string s, string t) {
10
+ if (s.size () == 0 || t.size () == 0 ) return 0 ;
11
+ if (t.size () > s.size ()) return 0 ;
12
+ vector<int > v (t.size (), 0 );
13
+ map<char , vector<int >> mp;
14
+ for (int i = 0 ; i < t.size (); i++)
15
+ mp[t[i]].push_back (i);
16
+ for (auto a : s) {
17
+ vector<int >& idx = mp[a];
18
+ for (auto it = idx.rbegin (); it != idx.rend (); it++)
19
+ if (*it == 0 ) v[*it]++;
20
+ else v[*it] += v[*it-1 ];
21
+ }
22
+
23
+ return v.back ();
24
+ }
25
+ };
26
+
27
+ int main () {
28
+ std::cout << Solution ().numDistinct (" ccc" , " c" ) << std::endl;
29
+ std::cout << Solution ().numDistinct (" ccc" , " cc" ) << std::endl;
30
+
31
+ return 0 ;
32
+ }
You can’t perform that action at this time.
0 commit comments