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:

  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.

Thoughts:

  1. dfs + use list to record tracking, use set to prevent redundance:
  2. Code: Java: Standard backtracking
class Solution {
    public List<List<Integer>> findSubsequences(int[] nums) {
        List<List<Integer>>res = new ArrayList<>();
        List<Integer> element = new ArrayList<>();
        dfs(res, element, 0, nums);

        return new ArrayList(res);

    }

    private void dfs(List<List<Integer>>res, List<Integer> element, int pos, int[] nums){
        if(element.size()>= 2) res.add(new ArrayList(element));
        Set<Integer> s = new HashSet<>(nums.length);
        for (int i  = pos; i < nums.length; i++){
            if ((element.size() == 0 || element.get(element.size() - 1) <= nums[i] )&& !s.contains(nums[i])){
                element.add(nums[i]);
                dfs(res, element, i + 1, nums);
                element.remove(element.size() - 1);
                s.add(nums[i]);
            }
        }
    }

}

Code: C++: Standard backtracking with hash checking

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

Using python itertools.combinations

class Solution(object):
    def findSubsequences(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        return [ x
                for i in range(2, len(nums) + 1)
                for x in set(itertools.combinations(nums,i))
                if all(a <= b for a, b in zip(x, x[1:]))
        ]

results matching ""

    No results matching ""