Increasing Subsequences
Description
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]]
Constraints:
- The length of the given array will not exceed 15.
- The range of integer in the given array is [-100,100].
- The given array may contain duplicates, and two equal integers should also be considered as a special case of increasing sequence.
Solution(javascript)
/** 这题该怎么去重???
* @param {number[]} nums
* @return {number[][]}
*/
const findSubsequences = function (nums) {
if (nums.length <= 1) {
return []
}
const result = []
const aux = (index, current = []) => {
if (index > nums.length - 1) {
if (current.length >= 2) {
result.push(current)
}
return
}
if (nums[index] >= current[current.length - 1]) {
aux(index + 1, current.concat(nums[index]))
aux(index + 1, current)
} else {
aux(index + 1, current)
}
}
for (let i = 0; i < nums.length; i++) {
aux(i + 1, [nums[i]])
}
const set = new Set()
return result.filter((xs = []) => {
const key = xs.join('.') // 这里要分隔,不然 2+32 与 23 + 2是一样的
if (!set.has(key)) {
set.add(key)
return true
}
return false
})
}