Leetcode 491.非递减子序列
题目要求
示例 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]]
回溯法

树层去重在for循环内设置终止条件
set用于判断该层是否用过该元素,用于去重
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
| class Solution { public List<List<Integer>> res = new ArrayList<List<Integer>>(); public List<Integer> path = new ArrayList<>(); public List<List<Integer>> findSubsequences(int[] nums) { backtrack(nums, 0); return res; }
public void backtrack(int[] nums, int startIndex) { if (path.size() > 1) { res.add(new ArrayList<>(path)); }
Set<Integer> set = new HashSet<>(); for (int i = startIndex; i < nums.length; i++) { if (!path.isEmpty() && nums[i] < path.get(path.size() - 1)) { continue; } if (set.contains(nums[i])) { continue; } path.add(nums[i]); set.add(nums[i]); backtrack(nums, i + 1); path.remove(path.size() - 1); } } }
|
代码随想录:使用map
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
| class Solution { List<List<Integer>> res = new ArrayList<>(); LinkedList<Integer> path = new LinkedList<>(); public List<List<Integer>> findSubsequences(int[] nums) { getSubsequences(nums,0); return res; } private void getSubsequences( int[] nums, int start ) { if(path.size()>1 ){ res.add( new ArrayList<>(path) ); } HashMap<Integer,Integer> map = new HashMap<>(); for(int i=start ;i < nums.length ;i++){ if(!path.isEmpty() && nums[i]< path.getLast()){ continue; } if ( map.getOrDefault( nums[i],0 ) >=1 ){ continue; } map.put(nums[i],map.getOrDefault( nums[i],0 )+1); path.add( nums[i] ); getSubsequences( nums,i+1 ); path.removeLast(); } } }
|