LeetCode 90. subset II JavaScript to achieve

topic

Given an array of integers nums may contain duplicate elements, which returns an array of all possible subsets (power set).

Description: Solution Set can not contain duplicate subsets.

Example:

Input: [1,2,2]
Output:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/subsets-ii
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

Thinking

This question obviously can use backtracking to solve, in LeetCode 78. subset , since no duplicate elements, so a direct backtracking can solve the problem, but in this question, because of repetitive elements, so backtracking process requires pruning
case backtracking not detailed here, to talk about pruning
such as the following array
[1,2,2,3]
when we go back to the third number is a number that is the subscript 2 time, we can choose to put 2 and 2 do not put the situation is [1,2,2], respectively, and [1,2], but in fact the case [1,2] and will choose not to put on the first step 2 in this step the number into the result of the third number is the same, to do so here a pruning process
, after understanding the above contents can be drawn, prune whether the currently selected condition is equal to the number of loaded step into the number

Implementation code

Direct implementation code 78. subset backtracking

var subsets = function(nums) {
    let result =[];
    let len = nums.length;
    function backTrack(arr,index){
        if(index===len){
            result.push(arr);
            return;
        }
        backTrack([...arr,nums[index]],index+1);
        backTrack(arr,index+1);
    }
    backTrack([],0)
    return result;
};

90. subset Ⅱ implementation code pruning method backtracking

var subsetsWithDup = function(nums) {
    let result =[];
    let len = nums.length;
    nums.sort((a,b)=>a-b);
    function backTrack(arr,index){
        if(index===len){
            result.push(arr);
            return;
        }
        backTrack([...arr,nums[index]],index+1);
        if(nums[index]!==arr[arr.length-1])
            backTrack(arr,index+1);
    }
    backTrack([],0)
    return result;
};
发布了178 篇原创文章 · 获赞 12 · 访问量 3万+

Guess you like

Origin blog.csdn.net/zemprogram/article/details/104085220