forked from arya2004/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathl.cpp
More file actions
43 lines (29 loc) · 978 Bytes
/
Copy pathl.cpp
File metadata and controls
43 lines (29 loc) · 978 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <bits/stdc++.h>
using namespace std;
int backtrack(vector<int> &arr, int i, int previous, vector<int>& sequence, vector<int>& temp) {
if (i >= arr.size()) {
if (temp.size() > sequence.size()) {
sequence = temp;
}
return 0;
}
int take = 0;
int dontTake = backtrack(arr, i + 1, previous, sequence, temp);
if (arr[i] > previous) {
temp.push_back(arr[i]);
take = 1 + backtrack(arr, i + 1, arr[i], sequence, temp);
temp.pop_back();
}
return max(take, dontTake);
}
int main() {
vector<int> a = {7, 2, 9, 1, 11, 5, 13, 19, 3, 20};
// Backtracking LIS
vector<int> backtrackSequence, temp;
int ans = backtrack(a, 0, INT_MIN, backtrackSequence, temp);
cout << "Max length (backtrack): " << backtrackSequence.size() << endl;
cout << "LIS (backtrack): ";
for (int num : backtrackSequence) cout << num << " ";
cout << endl;
return 0;
}