1. 程式人生 > >LeetCode-491. Increasing Subsequences

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]]
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); } }