博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode]3Sum
阅读量:4150 次
发布时间:2019-05-25

本文共 2076 字,大约阅读时间需要 6 分钟。

class Solution {public:	void threeSum(int step, int sum,				  vector
& path, vector
>& ans, const vector
& num, vector
& used) { if(path.size() == 3) { ans.push_back(path); return; } if(step >= num.size()) return; //1. not choose threeSum(step+1, sum, path, ans, num, used); //2. choose if(step != 0 && num[step] == num[step-1] && !used[step-1]) return;//avoid same combination if(path.size() == 2 && sum+num[step] != 0) return;//sum not equal to zero used[step] = true; path.push_back(num[step]); threeSum(step+1, sum+num[step], path, ans, num, used); used[step] = false; path.pop_back(); } vector
> threeSum(vector
&num) { // Start typing your C/C++ solution below // DO NOT write int main() function if(num.size() == 0) return vector
>(); sort(num.begin(), num.end()); vector
path; vector
> ans; vector
used(num.size(), false); threeSum(0, 0, path, ans, num, used); return ans; }};

second time

class Solution {public:    vector
> threeSum(vector
&num) { // Start typing your C/C++ solution below // DO NOT write int main() function sort(num.begin(), num.end()); vector
> ans; for(int i = 0; i < num.size(); ++i) { if(i != 0 && num[i] == num[i-1]) continue; int left = i+1; int right = num.size()-1; vector
triplet(3); while(left < right) { int sum = num[left]+num[right]+num[i]; if(sum > 0) right--; else if(sum < 0) left++; else { triplet[0] = num[i], triplet[1] = num[left], triplet[2] = num[right]; ans.push_back(triplet); //break; int oldLeftNum = num[left]; while(left < num.size() && num[left] == oldLeftNum) left++; } } } return ans; }};

转载地址:http://qaxti.baihongyu.com/

你可能感兴趣的文章
There's Much More than Intel/AMD Inside
查看>>
CentOS7 安装MySQL 5.6.43
查看>>
使用Java 导入/导出 Excel ----Jakarta POI
查看>>
本地tomcat 服务器内存不足
查看>>
IntelliJ IDAE 2018.2 汉化
查看>>
基于S5PV210的uboot移植中遇到的若干问题记录(一)DM9000网卡移植
查看>>
Openwrt源码下载与编译
查看>>
我和ip_conntrack不得不说的一些事
查看>>
Linux 查看端口使用情况
查看>>
文件隐藏
查看>>
两个linux内核rootkit--之二:adore-ng
查看>>
两个linux内核rootkit--之一:enyelkm
查看>>
关于linux栈的一个深层次的问题
查看>>
rootkit related
查看>>
配置文件的重要性------轻化操作
查看>>
又是缓存惹的祸!!!
查看>>
为什么要实现程序指令和程序数据的分离?
查看>>
我对C++ string和length方法的一个长期误解------从protobuf序列化说起(没处理好会引起数据丢失、反序列化失败哦!)
查看>>
一起来看看protobuf中容易引起bug的一个细节
查看>>
无protobuf协议情况下的反序列化------貌似无解, 其实有解!
查看>>