[LeetCode] 491. Increasing Subsequences

Given an integer array nums, return all the different possible non-decreasing subsequences of the given array with at least two elements. You may return the answer in any order.

Example 1:

Input: nums = [4,6,7,7]
Output: [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]

Example 2:

Input: nums = [4,4,3,2,1]
Output: [[4,4]]

Constraints:

  • 1 <= nums.length <= 15
  • -100 <= nums[i] <= 100

递增子序列。

给你一个整数数组 nums ,找出并返回所有该数组中不同的递增子序列,递增子序列中 至少有两个元素 。你可以按 任意顺序 返回答案。

数组中可能含有重复元素,如出现两个整数相等,也可以视作递增序列的一种特殊情况。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/non-decreasing-subsequences
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路是回溯 backtracking。还是会利用到经典的回溯模板,这道题只需要在几个地方略加修改即可。首先因为 input 里面会有重复的数字,如果是连在一起的相同数字,也会被视为递增,所以一定要用一个 hashset帮助去重。去重的方式有两种,一是在回溯的过程中进行去重,另一种是对结果集进行去重。我这里是对结果集进行去重。

其次回溯的 base case 是只要子集长度大于 1 就可以加入结果集。回溯的过程中,只要后一个数字 >= 前一个数字,就加入当前子集并进入下一层的递归。

时间O(2^n)

空间O(n)

Java实现

 1 class Solution {
 2     public List<List<Integer>> findSubsequences(int[] nums) {
 3         HashSet<List<Integer>> set = new HashSet<>();
 4         if (nums == null || nums.length < 2) {
 5             return new ArrayList<>();
 6         }
 7         helper(set, new ArrayList<>(), nums, 0);
 8         List<List<Integer>> res = new ArrayList<>(set);
 9         return res;
10     }
11 
12     private void helper(HashSet<List<Integer>> set, List<Integer> list, int[] nums, int start) {
13         if (list.size() >= 2) {
14             set.add(new ArrayList<>(list));
15             // 这里不能return因为还未结束
16         }
17         for (int i = start; i < nums.length; i++) {
18             if (list.size() == 0 || nums[i] >= list.get(list.size() - 1)) {
19                 list.add(nums[i]);
20                 helper(set, list, nums, i + 1);
21                 list.remove(list.size() - 1);
22             }
23         }
24     }
25 }

 

LeetCode 题目总结

posted @ 2020-09-27 04:04  CNoodle  阅读(135)  评论(0编辑  收藏  举报