给定一个整型数组, 你的任务是找到所有该数组的递增子序列,递增子序列的长度至少是2。
示例:
输入: [4, 6, 7, 7] 输出: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]] 说明:
给定数组的长度不会超过15。 数组中的整数范围是 [-100,100]。 给定数组中可能包含重复数字,相等的数字应该被视为递增的一种情况。
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/increasing-subsequences 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
public class IncreaseSubSequences { public static List<List<Integer>> findSubsequences(int[] nums) { int length = 2; List<List<Integer>> results = new LinkedList<>(); List<Integer> result = new LinkedList<>(); recursionFind(nums, 0, results, result); return results; } public static void recursionFind(int[] nums, int start, List<List<Integer>> results, List<Integer> result) { if (start == nums.length && result.size() > 1) { // 因为不放置的元素的数量是不确定的,所以要判断是否大于一 results.add(new LinkedList<>(result)); } else { if (start < nums.length) { if (result.size() == 0 || result.get(result.size() - 1) <= nums[start]) { result.add(nums[start]); // 放置当前的这个 recursionFind(nums, start + 1, results, result); result.remove(result.size() - 1); } // 不放置当前的这个,相同的元素不放置只考虑一次,避免重复 if (result.size() == 0 || result.get(result.size() - 1) != nums[start]) { recursionFind(nums, start + 1, results, result); } } } } public static void main(String[] args) { List<List<Integer>> results = findSubsequences(new int[]{4, 4, 6, 7}); for (List<Integer> temp : results) { System.out.println(temp); } } }