The problem is on LeetCode:
- Increasing Subsequences
Given an integer array, your task is to find all the different possible increasing subsequences of the given array, and the length of an increasing subsequence should be at least 2.
Example:
Input: [4, 6, 7, 7]
Output: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]]
I have wrote the same algorithm in C++ and Golang respectively.
The Golang version keeps getting TLE on the case [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]. But the C++ version worked well and beat 72% cpp solutions.
I had a hard time trying to find out what's wrong with the Golang version, so I really appreciate your help.
Here are my codes:
Golang:
func findSubsequences(nums []int) [][]int {
n := len(nums)
m := make(map[int]int)
cur := make([][]int, 1)
cur[0] = []int{}
var ans [][]int
for i := 0; i < n; i++ {
lim := len(cur)
st, ok := m[nums[i]]
if !ok {
st = 0
}
m[nums[i]] = lim
for j := st; j < lim; j++ {
if len(cur[j]) > 0 && nums[i] < cur[j][len(cur[j])-1] {
continue
}
tmp := append(cur[j], nums[i])
cur = append(cur, tmp)
if len(tmp) >= 2 {
ans = append(ans, tmp)
}
}
}
return ans
}
C++:
class Solution {
public:
vector<vector<int>> findSubsequences(vector<int>& nums) {
vector<vector<int>> ans, cur;
cur.push_back(vector<int>());
unordered_map<int, int> m;
int n = nums.size(), st;
for (int i = 0; i < n; ++i) {
if (m.count(nums[i]))
st = m[nums[i]];
else
st = 0;
int lim = cur.size();
m[nums[i]] = lim;
for (int j = st; j < lim; j++) {
if (cur[j].size() > 0 && nums[i] < cur[j].back())
continue;
cur.push_back(cur[j]);
cur.back().push_back(nums[i]);
if (cur.back().size() >= 2)
ans.push_back(cur.back());
}
}
return ans;
}
};