Skip to content

Commit 0b97b8d

Browse files
committed
Dynamic programming
Dynamic programming based on the brute-force recursive solutions.
1 parent a8279d6 commit 0b97b8d

File tree

5 files changed

+76
-0
lines changed

5 files changed

+76
-0
lines changed

Decode_Ways.cpp

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution {
2+
public:
3+
int numDecodings(string s) {
4+
if(s == "" || s[0] == '0') return 0;
5+
if(s.size() == 1) return 1;
6+
7+
vector<int> dp(s.size()+1);
8+
dp[s.size()] = 1;
9+
10+
for(int j = s.size()-1; j>=0; j--){
11+
if(s[j] == '0') {
12+
dp[j] = 0;
13+
continue;
14+
}
15+
16+
if(j < s.size()-1 && atoi(s.substr(j, 2).c_str()) <= 26){
17+
dp[j] = dp[j+1] + dp[j+2];
18+
}else{
19+
dp[j] = dp[j+1];
20+
}
21+
}
22+
return dp[0];
23+
}
24+
};

Distinct_Subsequences.cpp

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution {
2+
public:
3+
int numDistinct(string S, string T) {
4+
int m = S.size();
5+
int n = T.size();
6+
7+
vector<vector<int>> tbl(m+1, vector<int>(n+1, 0));
8+
9+
for(int i = 0; i <= m; i++){
10+
for(int j = 0; j <= n; j++){
11+
if(j == 0) tbl[i][j] = 1;
12+
if(i > 0 && j > 0){
13+
if(S[i-1] == T[j-1]){
14+
tbl[i][j] = tbl[i-1][j] + tbl[i-1][j-1];
15+
}else{
16+
tbl[i][j] = tbl[i-1][j];
17+
}
18+
}
19+
}
20+
}
21+
22+
return tbl[m][n];
23+
}
24+
};

Edit_Distance.cpp

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
public:
3+
int minDistance(string word1, string word2) {
4+
int m = word1.size();
5+
int n = word2.size();
6+
7+
vector<vector<int>> tbl(m+1, vector<int>(n+1, 0));
8+
9+
for(int i = 0; i <= m; i++){
10+
for(int j = 0; j <= n; j++){
11+
if(i == 0) tbl[i][j] = j;
12+
if(j == 0) tbl[i][j] = i;
13+
14+
if(i > 0 && j > 0){
15+
if(word1[i-1] == word2[j-1]){
16+
tbl[i][j] = tbl[i-1][j-1];
17+
}else{
18+
tbl[i][j] = min(min(tbl[i-1][j-1], tbl[i-1][j]), tbl[i][j-1])+1;
19+
}
20+
}
21+
}
22+
}
23+
24+
return tbl[m][n];
25+
}
26+
};

Longest_Palindromic_Substring.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,4 @@ class Solution {
4343
return s.substr(s_ind, max_len);
4444
}
4545
};
46+

Word_Break.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,4 @@ class Solution {
3131
return 0;
3232
}
3333
};
34+

0 commit comments

Comments
 (0)