LeetCode-491. Increasing Subsequences

来源:互联网 发布:陈默外推软件包月 编辑:程序博客网 时间:2024/05/17 08:12

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]]
Note:
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.

package solutions._491;import java.util.*;/** * 491. Increasing Subsequences */class Solution {    // 标记是否被访问过    private boolean visited[];    private Set<List<Integer>> result;    private LinkedList<Integer> cur;    private int len;    private void DFS(int[] nums, int i) {        // 遍历到最后一个元素则跳出        if (i == nums.length) {            cur.clear();            return;        }        // 超过两个元素则加入结果集中        if (len >= 2) {            List<Integer> list = new ArrayList<>();            Object[] objects = cur.toArray();            for (int j = objects.length - 1; j >= 0; j--) {                list.add((Integer) objects[j]);            }            result.add(list);        }        for (int j = i + 1; j < nums.length; j++) {            if (!visited[j] && (nums[j] >= cur.peek())) {                visited[j] = true;                cur.push(nums[j]);                len++;                DFS(nums, j);                // 回溯                cur.pop();                visited[j] = false;                len--;            }        }    }    public List<List<Integer>> findSubsequences(int[] nums) {        visited = new boolean[nums.length];        result = new HashSet<>();        cur = new LinkedList<>();        for (int i = 0; i < nums.length; i++) {            visited[i] = true;            cur.clear();            cur.push(nums[i]);            len = 1;            DFS(nums, i);        }//        result.forEach(System.out::println);        List<List<Integer>> lists = new ArrayList<>();        lists.addAll(result);        return lists;    }    public static void main(String[] args) {        Solution solution = new Solution();        int[] arr = {1,2,3,4,5,6,7,8,9,10,1,1,1,1,1};        List<List<Integer>> list = solution.findSubsequences(arr);        System.out.println(list);    }}
原创粉丝点击