78 Subsets

给定一组整数,返回所有可能的集合。

回溯法,深度优先遍历,faster than 98.7%

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var subsets = function(nums) {
    var res = []
    res.push([])
    if(nums.length === 0) return res
    dfs(nums, 0, [], res)
    return res
};
function dfs(nums, flag, sub, res){
    for(var i = flag; i < nums.length; i++){
        sub.push(nums[i])
        res.push(sub.slice())
        dfs(nums, i + 1, sub, res)
        sub.pop()
    }
}

你可能感兴趣的:(78 Subsets)