[LeetCode] 491. 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]]
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.
递增子序列。题意是给一个无序的整型int数组,请你返回所有递增的子序列。相等的元素也视为递增。
思路是回溯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 == 0) { 5 return new ArrayList<>(); 6 } 7 helper(set, new ArrayList<>(), nums, 0); 8 List 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() > 1) { 14 set.add(new ArrayList<>(list)); 15 } 16 for (int i = start; i < nums.length; i++) { 17 if (list.size() == 0 || list.get(list.size() - 1) <= nums[i]) { 18 list.add(nums[i]); 19 helper(set, list, nums, i + 1); 20 list.remove(list.size() - 1); 21 } 22 } 23 } 24 }
标签:set,nums,int,list,Subsequences,new,array,Increasing,LeetCode 来源: https://www.cnblogs.com/cnoodle/p/13737526.html