subsetII leetcode c++
2014-11-13 16:23
330 查看
I made two mistakes in this problem.
1.I forget to push_back the cur to answer when the cur.size() == num.
2.the change from this problem to subsets is just we need to write a judgement that in the same layer of the num, if S[i] == S[i-1] ,we just ignore the S[i].because this cause the duplicates. however,when I finished the judgement, I forget to write continue
to make this judgement take effect.class Solution {
public:
vector<vector<int> > subsetsWithDup(vector<int> &S) {
vector<vector<int>> answer;
vector<int> cur;
answer.push_back(cur);
if(S.empty())
return answer;
sort(S.begin(),S.end());
for(int i = 1;i<=S.size();i++)
dfs(0,i,S,cur,answer);
return answer;
}
void dfs(int start,int num,vector<int> &S,vector<int> &cur,vector<vector<int>> &answer)
{
if(cur.size() == num)
{
answer.push_back(cur);
return;
}
for(int i = start;i<S.size();i++)
{
if(i!= start && S[i] == S[i-1])
continue;
cur.push_back(S[i]);
dfs(i+1,num,S,cur,answer);
cur.pop_back();
}
}
};
1.I forget to push_back the cur to answer when the cur.size() == num.
2.the change from this problem to subsets is just we need to write a judgement that in the same layer of the num, if S[i] == S[i-1] ,we just ignore the S[i].because this cause the duplicates. however,when I finished the judgement, I forget to write continue
to make this judgement take effect.class Solution {
public:
vector<vector<int> > subsetsWithDup(vector<int> &S) {
vector<vector<int>> answer;
vector<int> cur;
answer.push_back(cur);
if(S.empty())
return answer;
sort(S.begin(),S.end());
for(int i = 1;i<=S.size();i++)
dfs(0,i,S,cur,answer);
return answer;
}
void dfs(int start,int num,vector<int> &S,vector<int> &cur,vector<vector<int>> &answer)
{
if(cur.size() == num)
{
answer.push_back(cur);
return;
}
for(int i = start;i<S.size();i++)
{
if(i!= start && S[i] == S[i-1])
continue;
cur.push_back(S[i]);
dfs(i+1,num,S,cur,answer);
cur.pop_back();
}
}
};
相关文章推荐
- LeetCode 142 — Linked List Cycle II(C++ Java Python)
- Leetcode_pascals-triangle-ii (updated c++ and python version)
- [C++]LeetCode: 72 Remove Duplicates from Sorted Array II
- [C++]LeetCode: 92 Unique Binary Search Trees II
- [C++]LeetCode: 91 Path Sum II
- Leetcode Subset I & II
- [C++]LeetCode: 113 Word Break II (DP && Backtacking) 求解拆分组合
- [C++]LeetCode: 62 Reverse Linked List II
- [C++]LeetCode: 44 Search in Rotated Sorted Array II
- pascal's triangle II leetcode c++
- Leetcode_best-time-to-buy-and-sell-stock-ii(c++ and python version)
- Path sum II |leetcode c++
- Leetcode_find-minimum-in-rotated-sorted-array-ii(c++ version)
- [C++]LeetCode: 67 Single Number II
- [C++]LeetCode: 32 Binary Tree Level Order Traversal II
- Leetcode_remove-duplicates-from-sorted-array-ii (c++ and python version)
- Subset II leetcode java
- [C++]LeetCode: 6 Remove Duplicates from Sorted List II
- [C++]LeetCode: 77 Best Time to Buy and Sell Stock II (贪心算法)
- [C++]LeetCode: 111 Spiral Matrix II (螺旋写入矩阵)