二分查找你学废了吗?快来看看这道题如何使用二分查找解决吧!
回溯算法练习题
LeetCode链接:491. 非递减子序列
1.题目描述
给你一个整数数组 nums ,找出并返回所有该数组中不同的递增子序列,递增子序列中 至少有两个元素 。你可以按 任意顺序 返回答案。
数组中可能含有重复元素,如出现两个整数相等,也可以视作递增序列的一种特殊情况。
示例 1:
示例 2:
1 2
| 输入:nums = [4,4,3,2,1] 输出:[[4,4]]
|
提示:
1 <= nums.length <= 15
-100 <= nums[i] <= 100
2.题解
2.1 回溯算法-哈希集合
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| class Solution { List<List<Integer>> result = new ArrayList<>(); List<Integer> path = new ArrayList<>();
public List<List<Integer>> findSubsequences(int[] nums) { backtracking(nums, 0); return result; }
public void backtracking(int[] nums, int start) { if (path.size() > 1) result.add(new ArrayList<>(path));
Set<Integer> set = new HashSet<>();
for (int i = start; i < nums.length; i++) { if ((!path.isEmpty() && nums[i] < path.get(path.size() - 1)) || set.contains(nums[i])) continue;
set.add(nums[i]); path.add(nums[i]); backtracking(nums, i + 1); path.remove(path.size() - 1); } } }
|
2.2 回溯算法-哈希数组
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| class Solution { List<List<Integer>> result = new ArrayList<>(); List<Integer> path = new ArrayList<>();
public List<List<Integer>> findSubsequences(int[] nums) { backtracking(nums, 0); return result; }
public void backtracking(int[] nums, int start) { if (path.size() > 1) result.add(new ArrayList<>(path));
boolean[] hash = new boolean[201];
for (int i = start; i < nums.length; i++) { if ((!path.isEmpty() && nums[i] < path.get(path.size() - 1)) || hash[nums[i] + 100]) continue;
hash[nums[i] + 100] = true; path.add(nums[i]); backtracking(nums, i + 1); path.remove(path.size() - 1); } } }
|