[Leetcode]491. 递增子序列

题目:

给你一个整数数组 nums ,找出并返回所有该数组中不同的递增子序列,递增子序列中 至少有两个元素 。你可以按 任意顺序 返回答案。

数组中可能含有重复元素,如出现两个整数相等,也可以视作递增序列的一种特殊情况。

示例 1:

输入:nums = [4,6,7,7]
输出:[[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]
示例 2:

输入:nums = [4,4,3,2,1]
输出:[[4,4]]
 

提示:

1 <= nums.length <= 15
-100 <= nums[i] <= 100

代码:


public class FindSubsequences {

    // 491. 递增子序列
    List<List<Integer>> result = new ArrayList<>();

    public List<List<Integer>> findSubsequences(int[] nums) {
        List<Integer> tempList = new ArrayList<>();
        findSubsequences(nums, 0, tempList);
        return result;
    }

    public void findSubsequences(int[] nums, int begin, List<Integer> tempList) {
        if (tempList.size() >= 2) {
            result.add(new ArrayList<>(tempList));
        }
        for (int i = begin; i < nums.length; i++) {
            int flag = 0;
            for (int j = i - 1; j >= begin; j--) {
                if (nums[i] == nums[j]) {
                    flag = 1;
                    break;
                }
            }
            if (flag == 1 || begin > 0 && nums[i] < nums[begin - 1]) {
                continue;
            }
            tempList.add(nums[i]);
            findSubsequences(nums, i + 1, tempList);
            tempList.remove(tempList.size() - 1);
        }
    }

    public static void main(String[] args) {
        //int[] nums = new int[]{4,6,7,7};  //[1,2,3,4,1,1]
        int[] nums = new int[]{4, 4, 3, 2, 1};
        FindSubsequences solution = new FindSubsequences();
        List<List<Integer>> result = solution.findSubsequences(nums);
        for (List<Integer> subList : result) {
            for (int i : subList) {
                System.out.print(i + " ");
            }
            System.out.print('\n');
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值