题目:
Given a collection of integers that might contain duplicates, S, return all possible subsets.
Note:
- Elements in a subset must be in non-descending order.
- The solution set must not contain duplicate subsets.
For example,
If S = [1,2,2], a solution is:
[ [2], [1], [1,2,2], [2,2], [1,2], [] ]
代码如下:
void getsubset(set<vector<int> > &subsets,vector<int> &S,int i)
{
vector<int> tmp;
for(int j=0;j<S.size();j++)
{
if(i&(1<<j))tmp.push_back(S[j]);
}
subsets.insert(tmp);
}
vector<vector<int> > subsetsWithDup(vector<int> &S) {
set<vector<int> > subsets;
set<vector<int> >::iterator j;
vector<vector<int> > result;
sort(S.begin(),S.end());
int n=S.size();
for(int i=0;i<1<<n;i++)
{
getsubset(subsets,S,i);
}
for(j=subsets.begin();j!=subsets.end();j++)
{
result.push_back(*j);
}
return result;
}
题目:
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 < = m < = n < = length of list.
代码如下:
ListNode *reverseBetween(ListNode *head, int m, int n) {
if(m==n)return head;
int i=1;
if(m==1)
{
ListNode *head1=head;
while(i<n)
{
ListNode *tmp=head1->next;
head1->next=tmp->next;
tmp->next=head;
head=tmp;
i++;
}
}
else
{
ListNode *head1=head;
while(i<m-1)
{
head1=head1->next;
i++;
}
ListNode *head2=head1->next;
while(i<n-1)
{
ListNode *tmp=head2->next;
head2->next=tmp->next;
tmp->next=head1->next;
head1->next=tmp;
i++;
}
}
return head;
}
题目:
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1 \ 2 / 3
return [1,3,2].
代码如下:
void getresult(TreeNode *root,vector<int> &result)
{
if(root==NULL)return;
if(root->left!=NULL)
{
getresult(root->left,result);
}
result.push_back(root->val);
if(root->right!=NULL)
{
getresult(root->right,result);
}
return;
}
vector<int> inorderTraversal(TreeNode *root) {
vector<int> result;
getresult(root,result);
return result;
}