leetcode491. 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:**

1.  The length of the given array will not exceed 15.
2.  The range of integer in the given array is [-100,100].
3.  The given array may contain duplicates, and two equal integers should also be considered as a special case of increasing sequence.

現有一個無序的整數數組,要求找到所有遞增的子序列。

思路和代碼

這裏採用深度優先的思路進行解決。先將數組按照從小到大排序,再從左往右遍歷數組,每個數字有兩種可能,分別是選中到子數組,或者不選中。將所有的結果收納即可獲得最終的結果集。

但是這裏存在一個去重問題,如[1,7,7]這樣的數組,按照上面的規則會生成如下的子序列[1,7], [1,7], [1,7,7]。因此在每一輪選擇的時候,都需要判斷一下該數字在這一輪是否已經被選中過了。在一個有序的數組中

其實按照規則來說,即使不將整數數組進行排序也是可以實現的。因爲記錄的每個當前的subsequence都是按照從小到大的遞增子序列,只要判斷當前的數字是否比遞增子序列大就可以了。

代碼如下:

    public List<List<Integer>> findSubsequences(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        findSubsequences(nums, new LinkedList<>(), 0, result);
        return result;
    }

    public void findSubsequences(int[] nums, LinkedList<Integer> subSequence, int startIndex, List<List<Integer>> result) {
        if (subSequence.size() >= 2) {
            result.add(new LinkedList<>(subSequence));
        }
        Set<Integer> used = new HashSet<>();
        for (int i = startIndex ; i<nums.length ; i++) {
            if (used.contains(nums[i])) {continue;}
            if (subSequence.size() == 0 || nums[i] >= subSequence.peekLast()) {
                used.add(nums[i]);
                subSequence.add(nums[i]);
                findSubsequences(nums, subSequence, i+1, result);
                subSequence.removeLast();
            }

        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章