Leetcode 491.递增子序列

递增子序列

给定一个整型数组, 你的任务是找到所有该数组的递增子序列,递增子序列的长度至少是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]]

说明:

  1. 给定数组的长度不会超过15。
  2. 数组中的整数范围是 [-100,100]。
  3. 给定数组中可能包含重复数字,相等的数字应该被视为递增的一种情况。

思路:

利用递归的思想,维护一个栈,将每次找到的比当前栈顶大的数,然后入栈,将更新过后的栈扔进递归函数,然后更新查找的初始位置即从当前的位置后一个位置开始查找。递归函数结束后,取出栈顶,进入下个循环,这样将所有元素都作为栈底元素遍历一遍。

 1 import java.util.ArrayList;
 2 import java.util.HashSet;
 3 import java.util.List;
 4 import java.util.Set;
 5 
 6 public class Solution {
 7     public List<List<Integer>> findSubsequences(int[] nums) {
 8         Set<List<Integer>> res = new HashSet<List<Integer>>();
 9         helper(res, new ArrayList<Integer>(), nums, 0);
10         return new ArrayList<List<Integer>>(res);
11     }
12 
13     private void helper(Set<List<Integer>> res, List<Integer> subList, int[] nums, int start) {
14         if (subList.size() >= 2) {
15             res.add(new ArrayList<Integer>(subList));
16         }
17         for (int i = start; i < nums.length; i++) {
18             if (subList.size() == 0 || subList.get(subList.size() - 1) <= nums[i]) {
19                 subList.add(nums[i]);
20                 helper(res, subList, nums, i + 1);
21                 subList.remove(subList.size() - 1);
22             }
23         }
24     }
25 }

猜你喜欢

转载自www.cnblogs.com/kexinxin/p/10372504.html