491. 递增子序列
本题求自增子序列,是不能对原数组进行排序的,排完序的数组都是自增子序列了。
所以不能使用之前的去重逻辑!使用used数组做去重!
/**
* @param {number[]} nums
* @return {number[][]}
*/
var findSubsequences = function (nums) {
let result = []
let path = []
const backtracing = function (startIndex) {
// 除了第一层叶子节点其余都要
if (path.length > 1) {
result.push([...path])
}
let used = []
for (let i = startIndex; i < nums.length; i++) {
if ((path.length > 0 && nums[i] < path[path.length - 1]) || used[nums[i] + 100]) {
continue
}
used[nums[i] + 100] = true
path.push(nums[i])
backtracing(i + 1)
path.pop()
}
}
backtracing(0)
return result
};
46. 全排列
和组合问题最大的不同就是for循环里不用startIndex了。
而used数组,其实就是记录此时path里都有哪些元素使用了,一个排列里一个元素只能使用一次。
/**
* @param {number[]} nums
* @return {number[][]}
*/
var permute = function (nums) {
let result = [], path = [], used = []
const backtracing = function () {
if (path.length === nums.length) {
result.push([...path])
return
}
for (let i = 0; i < nums.length; i++) {
if (used[i]) continue
path.push(nums[i])
used[i] = true
backtracing()
path.pop()
used[i] = false
}
}
backtracing()
return result
};
47.全排列II
需要考虑去重,去重一定要对元素进行排序,这样我们才方便通过相邻的节点来判断是否重复使用了。
/**
* @param {number[]} nums
* @return {number[][]}
*/
var permuteUnique = function (nums) {
nums.sort((a, b) => a - b)
let result = [], path = [], used = []
const backtracing = function () {
if (path.length === nums.length) {
result.push(Array.from(path))
return
}
for (let i = 0; i < nums.length; i++) {
if (i > 0 && nums[i] === nums[i - 1] && !used[i - 1]) {
continue
}
if (!used[i]) {
used[i] = true
path.push(nums[i])
backtracing(used)
path.pop()
used[i] = false
}
}
}
backtracing()
return result
};