491.递增子序列
思路:
注意该数组不能设置为有序数组 也就不能用used去标记使用过的元素了
代码实现:
var subsetsWithDup = function (nums) {
let result = [], path = [];
let len = nums.length
let used = new Array(len).fill(false)
nums = nums.sort((a, b) => a - b)
const backTracking = (startIndex, used) => {
result.push([...path]);
for (let i = startIndex; i < nums.length; i++) {
if (i > 0 && nums[i - 1] === nums[i] && used[i - 1] === false) {
continue
}
used[i] = true
path.push(nums[i]);
backTracking(i + 1, used)
used[i] = false
path.pop()
}
}
backTracking(0, used)
return result
};
46.全排列
思路: 用一个标记数组 标记已经使用过的元素
代码实现
var permute = function (nums) {
let result = [], path = [];
let used = new Array(nums.length).fill(false)
const backTracking = (used) => {
if (path.length === nums.length) {
result.push([...path]);
return;
}
for (let i = 0; i < nums.length; i++) {
if (used[i] === true) continue
used[i] = true;
path.push(nums[i]);
backTracking(used)
used[i] = false;
path.pop()
}
}
backTracking(used);
return result
};
47.全排列 II
思路:
需要对原数组进行排序 才方便去重
代码实现:
var permuteUnique = function (nums) {
nums.sort((a, b) => {
return a - b
})
let result = [], path = [];
let used = []
const backTracking = (used) => {
if (nums.length === path.length) {
result.push([...path]);
return;
}
for (let i = 0; i < nums.length; i++) {
if (i > 0 && nums[i] === nums[i - 1] && used[i - 1] === false) continue
if (!used[i]) {
used[i] = true;
path.push(nums[i]);
backTracking(used);
path.pop();
used[i] = false
}
}
}
backTracking(used);
return result;
};
总结:继续加油!