In this Leetcode Increasing Subsequences problem solution Given an integer array nums, return all the different possible increasing subsequences of the given array with at least two elements. You may return the answer in any order.

The given array may contain duplicates, and two equal integers should also be considered a special case of increasing sequence.

Leetcode Increasing Subsequences problem solution


Problem solution in Python.

def findSubsequences(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """

        length = len(nums)
        ans = set()

        def dfs(index, res):
            res += "," + str(nums[index])
            if len(res.split(",")) > 2:
                ans.add(res)
            for i in range(index + 1, length):
                if nums[i] >= nums[index]:
                    dfs(i, res)

        for i in range(length):
            dfs(i, "")
        return [[int(item) for item in x.split(",")[1:]] for x in list(ans)]


Problem solution in Java.

public List<List<Integer>> findSubsequences(int[] nums) {
        Set<List<Integer>> set = new HashSet();
        for(int i = 0; i < nums.length; i++) {
            Set<List<Integer>> ts = new HashSet();
            List<Integer> t = new ArrayList();
            t.add(nums[i]);
            ts.add(t);
            dfs(nums, i + 1, ts);
            set.addAll(ts);
        }
        return set.stream().filter(l -> l.size() > 1).collect(Collectors.toList());
    }
    
    public void dfs(int[] a, int i, Set<List<Integer>> set) {
        if(i >= a.length) {
            return;
        }
        Set<List<Integer>> s = new HashSet();
        for(List<Integer> l : set) {
            if(l.get(l.size() - 1) <= a[i]) {
                List<Integer> t = new ArrayList(l);
                t.add(a[i]);
                s.add(t);
            }
        }
        set.addAll(s);
        dfs(a, i + 1, set);
    }


Problem solution in C++.

class Solution {
public:
    vector<vector<int>> findSubsequences(vector<int>& nums) {
        vector<vector<int>> res;
        vector<int> seq;
        dfs(res, seq, nums, 0);
        return res;
    }
    
    void dfs(vector<vector<int>>& res, vector<int>& seq, vector<int>& nums, int pos) {
        if(seq.size() > 1) res.push_back(seq);
        unordered_set<int> hash;
        for(int i = pos; i < nums.size(); ++i) {
            if((seq.empty() || nums[i] >= seq.back()) && hash.find(nums[i]) == hash.end()) {
                seq.push_back(nums[i]);
                dfs(res, seq, nums, i + 1);
                seq.pop_back();
                hash.insert(nums[i]);
            }
        }
    }
};