Skip to content

Commit 44855cf

Browse files
Merge pull request #502 from vishwajeet-hogale/main
Added more problems from leetcode.
2 parents 4d2f4c8 + 5cb03ad commit 44855cf

File tree

3 files changed

+84
-0
lines changed

3 files changed

+84
-0
lines changed

CPP/arrays/Two sum 2/twoSum.cpp

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
#include<iostream>
2+
#include<bits/stdc++.h>
3+
using namespace std;
4+
vector<int> twoSum(vector<int>& numbers, int target) {
5+
vector<int> res;
6+
int n = numbers.size();
7+
int low = 0,high = n - 1;
8+
while(low<high){
9+
int sum = numbers[low] + numbers[high];
10+
if(sum>target)
11+
high -= 1;
12+
else if(sum<target)
13+
low += 1;
14+
else{
15+
res.push_back(low+1);
16+
res.push_back(high+1);
17+
break;
18+
}
19+
}
20+
return res;
21+
}
22+
int main(){
23+
24+
vector<int> numbers({2,3,4});
25+
int target = 6;
26+
vector<int> res = twoSum(numbers,target);
27+
for(auto x:res)
28+
cout<<x<<endl;
29+
return 0;
30+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
#include<iostream>
2+
#include<bits/stdc++.h>
3+
using namespace std;
4+
int dp[31][1001] = {0}; // Table of n * target sum ; This is used to save the results in bottom up approach
5+
int numRollsToTarget(int n, int k, int target) {
6+
dp[0][0] = 1; // When you have 0 dices and target sum = 0; the number of ways to get the answer is 1
7+
8+
for(int i = 1;i<=target;i++){ // when you have 0 dices; [1,targetsum] numbers there are zero ways to get the answer
9+
dp[0][i] = 0;
10+
}
11+
for(int i=1;i<=n;i++){ // when you have 0 target; n =[1,n] dices there are zero ways to get the answer
12+
dp[i][0] = 0;
13+
}
14+
15+
/*
16+
The below loop has Time complexity = O(n*targetSum*k)
17+
It finds the answer for smaller target sums and build up to find the solution of the targetSum
18+
*/
19+
for(int i=1;i<=n;i++){
20+
for(int j=1;j<=target;j++){
21+
long long res = 0;
22+
for(int x=1;x<=k;x++){
23+
if(j>=x){
24+
res = (res % 1000000007) + (dp[i-1][j-x] % 1000000007);
25+
// res = res % 1000000007;
26+
}
27+
}
28+
dp[i][j] = res ;
29+
}
30+
}
31+
return dp[n][target] % 1000000007;
32+
}
33+
34+
int main(){
35+
36+
int n = 7,k=6,target = 30;
37+
cout<<numRollsToTarget(n,k,target)<<endl;
38+
return 0;
39+
}

Trees/pathSum.cpp

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
#include<iostream>
2+
#include<bits/stdc++.h>
3+
using namespace std;
4+
struct TreeNode{
5+
int val;
6+
TreeNode *left,*right;
7+
};
8+
bool hasPathSum(TreeNode* root, int sum) {
9+
if(!root)
10+
return 0;
11+
12+
if(!root->left && !root->right) // checks if the sum at the root is equal to target sum
13+
return sum-root->val == 0;
14+
return hasPathSum(root->left,sum-root->val) || hasPathSum(root->right,sum-root->val); // Traverses the tree to find the solution at one of the leaf nodes
15+
}

0 commit comments

Comments
 (0)