Tcdian / keep

今天不想做,所以才去做。
MIT License
5 stars 1 forks source link

78. Subsets #254

Open Tcdian opened 4 years ago

Tcdian commented 4 years ago

78. Subsets

给定一组 不含重复元素 的整数数组 nums,返回该数组所有可能的子集(幂集)

说明:解集不能包含重复的子集。

Example

Input: nums = [1,2,3]
Output:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]
Tcdian commented 4 years ago

Solution

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var subsets = function(nums) {
    const result = [[]];
    const subSet = [];
    backtracking(0);
    return result;

    function backtracking(index) {
        if (index >= nums.length) {
            return;
        }
        subSet.push(nums[index]);
        result.push([...subSet]);
        backtracking(index + 1);
        subSet.pop();
        backtracking(index + 1);
    }
};
function subsets(nums: number[]): number[][] {
    const result: number[][] = [[]];
    const subSet: number[] = [];
    backtracking(0);
    return result;

    function backtracking(index: number) {
        if (index >= nums.length) {
            return;
        }
        subSet.push(nums[index]);
        result.push([...subSet]);
        backtracking(index + 1);
        subSet.pop();
        backtracking(index + 1);
    }
};