【Leetcode】491. Increasing Subsequences

Question

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.

Analysis

遞歸回溯(DFS)找到所有的遞增子序列,使用set來自動去除重復的項。

Solution

class Solution {
    public List<List<Integer>> findSubsequences(int[] nums) {
        Set<List<Integer>> res = new HashSet<>();
        List<Integer> holder = new ArrayList<>();
        findSubsequence(res,holder,0,nums);
        List ans = new ArrayList(res);
        return ans;
    }
    private void findSubsequence(Set<List<Integer>> res,List<Integer>  holder,int index, int[] nums){
        if(holder.size() >= 2){
            res.add(new ArrayList(holder));
        }
        for(int i = index;i<nums.length;i++){
            if(holder.size()==0 || holder.get(holder.size()-1) <= nums[i]){
                holder.add(nums[i]);
                findSubsequence(res,holder,i+1,nums);
                holder.remove(holder.size()-1);
            }
        }
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗。 張土汪:刷leetcod...
    土汪閱讀 12,776評論 0 33
  • wordpress優化,主要是放在當前主題下的functions.php下
    malingxin閱讀 881評論 0 3
  • 劉溪,遠大住工國際;國學踐行23期學員,24期奉獻者,六項精進299期同修【知~學習》 【日精進第10天】 《六項...
    西西_3e45閱讀 136評論 0 0
  • 就在那一刻,安吉列娜將自己的心一寸寸冷凍起來,她再也不想讓陽光射入那個角落,明明互相說的都是祝福對方的話語,可安吉...
    Sunsy閱讀 321評論 0 0
  • 每個人都喜歡按時間來做一個結束,做一個開始。尤其是每一年的1月1日,是一個大開始,大家都在那是立下新年愿望,新年目...
    茶茶蘇閱讀 233評論 0 0