https://leetcode.com/problems/subsets/description/
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],
[]
]
Since this problem is seeking Subset
not Extreme Value
, dynamic programming is not an ideal solution. Other approaches should be taken into our consideration.
Actually, there is a general approach to solve problems similar to this one -- backtracking. Given a Code Template here, it demonstrates how backtracking works with varieties of problems. Apart from current one, many problems can be solved by such a general approach. For more details, please check the Related Problems
section below.
Given a picture as followed, let's start with problem-solving ideas of this general solution.
See Code Template details below.
- Backtrack Approach
- Backtrack Code Template/ Formula
- Supported Language:JS,C++
JavaScript Code:
/*
* @lc app=leetcode id=78 lang=javascript
*
* [78] Subsets
*
* https://leetcode.com/problems/subsets/description/
*
* algorithms
* Medium (51.19%)
* Total Accepted: 351.6K
* Total Submissions: 674.8K
* Testcase Example: '[1,2,3]'
*
* 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],
* []
* ]
*
*/
function backtrack(list, tempList, nums, start) {
list.push([...tempList]);
for(let i = start; i < nums.length; i++) {
tempList.push(nums[i]);
backtrack(list, tempList, nums, i + 1);
tempList.pop();
}
}
/**
* @param {number[]} nums
* @return {number[][]}
*/
var subsets = function(nums) {
const list = [];
backtrack(list, [], nums, 0);
return list;
};
C++ Code:
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
auto ret = vector<vector<int>>();
auto tmp = vector<int>();
backtrack(ret, tmp, nums, 0);
return ret;
}
void backtrack(vector<vector<int>>& list, vector<int>& tempList, vector<int>& nums, int start) {
list.push_back(tempList);
for (auto i = start; i < nums.size(); ++i) {
tempList.push_back(nums[i]);
backtrack(list, tempList, nums, i + 1);
tempList.pop_back();
}
}
};
- 39.combination-sum(chinese)
- 40.combination-sum-ii(chinese)
- 46.permutations(chinese)
- 47.permutations-ii(chinese)
- 90.subsets-ii
- 113.path-sum-ii(chinese)
- 131.palindrome-partitioning(chinese)