https://leetcode.com/problems/number-of-longest-increasing-subsequence/description/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int findNumberOfLIS(vector<int>& nums) {
if (nums.size() == 0)
return 0;
vector<pair<int, int>> LISInfo (nums.size(), make_pair(1, 1));
for (unsigned int i = 0; i < nums.size(); i++) {
for (unsigned int j = 0; j < i; j++) {
if (nums[j] < nums[i]) {
if ((LISInfo[j].first + 1) > LISInfo[i].first) {
LISInfo[i].first = LISInfo[j].first + 1;
LISInfo[i].second = LISInfo[j].second;
} else if ((LISInfo[j].first + 1) == LISInfo[i].first) {
LISInfo[i].second += LISInfo[j].second;
}
}
}
}
sort(LISInfo.begin(), LISInfo.end());
int total = LISInfo[nums.size() - 1].second;
int max = LISInfo[nums.size() - 1].first;
for (int i = nums.size() - 2; i >= 0; i--) {
if (LISInfo[i].first == max) {
total += LISInfo[i].second;
} else {
break;
}
}
cout << total << "\n";
return total;
}
};
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int findNumberOfLIS(vector<int>& nums) {
if (nums.size() == 0)
return 0;
vector<pair<int, int>> LISInfo (nums.size(), make_pair(1, 1));
for (unsigned int i = 0; i < nums.size(); i++) {
for (unsigned int j = 0; j < i; j++) {
if (nums[j] < nums[i]) {
if ((LISInfo[j].first + 1) > LISInfo[i].first) {
LISInfo[i].first = LISInfo[j].first + 1;
LISInfo[i].second = LISInfo[j].second;
} else if ((LISInfo[j].first + 1) == LISInfo[i].first) {
LISInfo[i].second += LISInfo[j].second;
}
}
}
}
sort(LISInfo.begin(), LISInfo.end());
int total = LISInfo[nums.size() - 1].second;
int max = LISInfo[nums.size() - 1].first;
for (int i = nums.size() - 2; i >= 0; i--) {
if (LISInfo[i].first == max) {
total += LISInfo[i].second;
} else {
break;
}
}
cout << total << "\n";
return total;
}
};
留言
張貼留言