LeetCode-78-Subset

算法描述:

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: nums = [1,2,3]
Output:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

解题思路:题目要求所有可能的子集,因此首先想到回溯法求解。注意边界,以及返回问题。

    vectorint>> subsets(vector<int>& nums) {
        vectorint>> results;
        vector<int> temp;
        backtracking(nums,results, temp, 0);
        return results;
    }
    
    void backtracking(vector<int>& nums, vectorint>>& results, vector<int>& temp, int index){
        if(temp.size() <= nums.size()){
            results.push_back(temp);
        }
        if(temp.size()==nums.size()) return;
        
        for(int i=index; i < nums.size();i++){
            temp.push_back(nums[i]);
            backtracking(nums, results, temp, i+1);
            temp.pop_back();
        }
    }

 

转载于:https://www.cnblogs.com/nobodywang/p/10344825.html

你可能感兴趣的:(数据结构与算法)