Java 29ms iterative solution


  • 0
    A
    public class Solution {
        public List<List<Integer>> findSubsequences(int[] nums) {
            int len = nums.length;
            List<List<Integer>> res = new LinkedList<>();
            if (len < 2)
                return res;
            List<List<Integer>>[] lists = new List[len];
            // false: include self single seq on this number
            boolean[] excludeSelf = new boolean[len];
            for (int i = 0; i < len; i++) {
                lists[i] = new LinkedList<>();
                int num = nums[i];
                for (int j = i - 1; j >= 0; j--) {
                    if (nums[j] <= num) {
                        List<Integer> sub;
                        if (!excludeSelf[j]) {
                            sub = new ArrayList<>();
                            sub.add(nums[j]);
                            sub.add(num);
                            lists[i].add(sub);
                        }
                        for (List<Integer> pre : lists[j]) {
                            sub = new ArrayList<>(pre);
                            sub.add(num);
                            lists[i].add(sub);
                        }
                    }
                    if (nums[j] == num) {
                        excludeSelf[i] = true;
                        break;
                    }
                }
            }
            for (List<List<Integer>> list : lists) {
                res.addAll(list);
            }
            return res;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.