Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

子集 II #27

Open
Mooo-star opened this issue Jul 5, 2024 · 1 comment
Open

子集 II #27

Mooo-star opened this issue Jul 5, 2024 · 1 comment
Labels
回溯 回溯算法 算法 记录算法

Comments

@Mooo-star
Copy link
Owner

给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的
子集
(幂集)。

解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。

示例 1:

输入:nums = [1,2,2]
输出:[[],[1],[1,2],[1,2,2],[2],[2,2]]

示例 2:

输入:nums = [0]
输出:[[],[0]]

@Mooo-star Mooo-star added 回溯 回溯算法 算法 记录算法 labels Jul 5, 2024
@Mooo-star
Copy link
Owner Author

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var subsetsWithDup = function (nums) {
    const result = []
    const len = nums.length
    const path = []
    // 排序
    nums.sort((a, b) => a - b)

    function backtack(startIndex) {
        result.push([...path])

        for (let i = startIndex; i < len; i++) {
            if (i > startIndex && nums[i] === nums[i - 1]) continue

            path.push(nums[i])
            backtack(i + 1)
            path.pop()
        }
    }

    backtack(0)
    
    return result
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
回溯 回溯算法 算法 记录算法
Projects
None yet
Development

No branches or pull requests

1 participant