leetcode_491. 递增子序列 python3
2020-08-25 22:31
1211 查看
目录
一、题目内容
给定一个整型数组, 你的任务是找到所有该数组的递增子序列,递增子序列的长度至少是2。
示例:
输入: [4, 6, 7, 7]
输出: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]]
说明:
给定数组的长度不会超过15。
数组中的整数范围是 [-100,100]。
给定数组中可能包含重复数字,相等的数字应该被视为递增的一种情况。
二、解题思路
1.回溯法:每一次添加的元素需要和上一个子序列的最后一个元素比较大小,大于等于则加入到新的子序列中去。
2.由于不能出现重复的子序列,因此需要检验子序列是否在之前被回溯过,若被回溯过则跳过(continue)。
三、代码
[code]class Solution: def findSubsequences(self, nums): ans = [] n = len(nums) def iter_find(i, sublist, n): if i > n: return if len(sublist) >= 2: ans.append(sublist) temp = [] for index in range(i, n): if nums[index] in temp: continue temp.append(nums[index]) if len(sublist) == 0 or nums[index] >= sublist[-1]: iter_find(index + 1, sublist + [nums[index]], n) iter_find(0, [], n) return ans if __name__ == '__main__': nums = [4,3,2,1] s = Solution() ans = s.findSubsequences(nums) print(ans)
悲恋花丶无心之人 CSDN认证博客专家 TensorFlow 深度学习 神经网络 计算机视觉在读研究生,熟悉Pytorch,MXNet,TensorFlow,Keras等深度学习框架,主要涉及的领域有目标检测,语义分割,超分辨率重建,行人重识别等。
相关文章推荐
- 用python写leetcode【7】 --两个数组的交集 II(350)、递增的三元子序列(334)
- leetcode--最长连续递增序列--python
- 【LeetCode】Python实现-674. 最长连续递增序列
- [LeetCode] Longest Increasing Subsequence 最长递增子序列的长度
- LeetCode || 34. 递增的三元子序列
- 用python写leetcode【16】 -- 最长连续序列(230)
- Leetcode 最长连续递增序列
- leetcode(674) 最长连续递增序列
- LeetCode:最长连续递增序列
- leetcode第115题 不同的子序列 python解法(用时48ms)
- [Swift]LeetCode1121. 将数组分成几个递增序列 | Divide Array Into Increasing Sequences
- Leetcode39.+Leetcode491. 回溯法之应用(三):寻找组合和+求递增子数列
- [LeetCode] 673. Number of Longest Increasing Subsequence 最长递增序列的个数
- Leetcode 300. Longest Increasing Subsequence 最长的递增子序列 dp
- leetcode--中级算法--数组和字符串--递增的三元子序列(JavaScript)
- [LeetCode] 674. Longest Continuous Increasing Subsequence 最长连续递增序列
- LeetCode--Longest Increasing Subsequence (最长递增子序列)Python
- LeetCode-Python-187. 重复的DNA序列
- 最长递增自序列 python
- leetcode 第105题(从前序与中序遍历序列构造二叉树) ,第106题(从中序与后序遍历序列构造二叉树)python解法(用时40ms)