All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0401_0500.s0491_increasing_subsequences.Solution Maven / Gradle / Ivy

There is a newer version: 1.37
Show newest version
package g0401_0500.s0491_increasing_subsequences;

// #Medium #Array #Hash_Table #Bit_Manipulation #Backtracking
// #2022_07_21_Time_24_ms_(38.30%)_Space_68.7_MB_(63.52%)

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@SuppressWarnings("java:S5413")
public class Solution {
    public List> findSubsequences(int[] nums) {
        if (nums == null || nums.length == 1) {
            return new ArrayList<>();
        }
        Set> answer = new HashSet<>();
        List list = new ArrayList<>();
        return new ArrayList<>(backtracking(nums, 0, list, answer));
    }

    private Set> backtracking(
            int[] nums, int start, List currList, Set> answer) {
        if (currList.size() >= 2) {
            answer.add(new ArrayList<>(currList));
        }
        for (int i = start; i < nums.length; i++) {
            if (currList.isEmpty() || currList.get(currList.size() - 1) <= nums[i]) {
                currList.add(nums[i]);
                backtracking(nums, i + 1, currList, answer);
                currList.remove(currList.size() - 1);
            }
        }
        return answer;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy