回溯算法 的最后一天!
題目鏈接:491. 非遞減子序列
狀態(tài):套用模版,直接AC。
在90.子集II 中我們是通過排序骂铁,再加一個(gè)標(biāo)記數(shù)組來達(dá)到去重的目的。
而本題求自增子序列,是不能對(duì)原數(shù)組進(jìn)行排序的痴昧,排完序的數(shù)組都是自增子序列了。
所以不能使用之前的去重邏輯冠王!
為了有鮮明的對(duì)比赶撰,用[4, 7, 6, 7]舉例:
解釋:稍后補(bǔ)充
完整代碼如下:
class Solution { // Java
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> findSubsequences(int[] nums) {
backTracking(nums, 0);
return result;
}
private void backTracking(int[] nums, int startIndex){
if(path.size() >= 2)
result.add(new ArrayList<>(path));
HashSet<Integer> hs = new HashSet<>();
for(int i = startIndex; i < nums.length; i++){
if(!path.isEmpty() && path.get(path.size() -1 ) > nums[i] || hs.contains(nums[i]))
continue;
hs.add(nums[i]);
path.add(nums[i]);
backTracking(nums, i + 1);
path.remove(path.size() - 1);
}
}
}