给你一个整数数组 nums
,找出并返回所有该数组中不同的递增子序列,递增子序列中 至少有两个元素 。你可以按 任意顺序 返回答案。
数组中可能含有重复元素,如出现两个整数相等,也可以视作递增序列的一种特殊情况。
示例 1:
输入:nums = [4,6,7,7] 输出:[[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]
示例 2:
输入:nums = [4,4,3,2,1] 输出:[[4,4]]
提示:
1 <= nums.length <= 15
-100 <= nums[i] <= 100
题解:
回溯法:
func findSubsequences(nums []int) [][]int {
var path []int
var result [][]int
var backtracking func(nums []int, startIndex int)
backtracking = func(nums []int, startIndex int) {
if len(path) > 1 {
tmp := make([]int, len(path))
copy(tmp, path)
result = append(result, tmp)
}
used := make(map[int]bool, len(nums))
for i := startIndex; i < len(nums); i++ {
if len(path) > 0 && nums[i] < path[len(path)-1] {
continue
}
if used[nums[i]] {
continue
}
used[nums[i]] = true
path = append(path, nums[i])
backtracking(nums, i+1)
path = path[:len(path)-1]
}
}
backtracking(nums, 0)
return result
}
评论前必须登录!
注册