ThreeSum
题目描述 Description
假设n个整数数组S, a、b、c均为数组S中的元素,要求找出不重复的序列,其中a + b + c = 0,并且要求为非递减序列(即a<=b<=c)
输入描述 Input Description
第一行输入一个数n,第二行依次输入n个元素。
输出描述 Output Description
每一行输出一个不重复且满足a+b+c=0的序列。
样例输入 Sample Input
6
-1 0 1 2 -1 -4
样例输出 Sample Output
-1 0 1
-1 -1 2
[解题思路]
用深度搜索即可,遍历数组S,找到a、b、c三个数相加等于0的序列 ,并把这个序列按字典序排列,通过STL里的sort即可,并判断是否重复,若不重复就是一个答案序列。下面的解法用的是vector容器,因为在排序,和判断是否重复的时候,用STL里的find和sort会方便很多。
[代码实现]
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int S[101]; /* 存放数组 */
int Book[101]; /* 标记是否以用 */
int num; /* 一共多少个元素 */
vector<int> Temp(3); /* 存放三个元素a,b,c */
vector<vector<int>> ans;/* 存放所有符合条件的序列,用于判断是否重复 */
bool IsZero() /* 判断是a+b+c==0 */
{
int sum=0;
for(vector<int>::iterator it=Temp.begin();it!=Temp.end();it++)
{
sum+=(*it);
}
if(sum == 0)
return true;
else
return false;
}
bool IsRepeat() /* 检查是否重复,另一种方法是全部存在一起,最后去重unique */
{
std::sort(Temp.begin(),Temp.end()); /* 按字典序排序 */
for(vector<vector<int>>::iterator it=ans.begin();it!=ans.end();it++)
{
if(Temp == (*it)) /* 如果重复直接返回false */
return false;
}
ans.push_back(Temp); /* 否则存入ans中 */
return true;
}
void Print()
{
for(vector<int>::iterator it=Temp.begin();it!=Temp.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
}
void Input()
{
cin>>num;
for(int i=0;i<num;i++)
cin>>S[i];
}
int dfs(int step)
{
if(step == 3) /* a b c 三个数 */
{
if(IsZero() && IsRepeat()) /* 判断三个数之和是否为0和是否重复 */
{
Print(); /* 显示在屏幕上 */
}
return 0;
}
for(int i=0;i<num;i++)
{
if(!Book[i])
{
Book[i] = 1;
Temp[step] = S[i];
dfs(step + 1);
Book[i] = 0;
}
}
}
int main()
{
Input();
dfs(0);
return 0;
}