题解 | #三数之和#

三数之和

https://www.nowcoder.com/practice/345e2ed5f81d4017bbb8cc6055b0b711

先排序,以便去重,然后采用递归求解
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
		Arrays.sort(num);
		System.out.println("num = " + Arrays.toString(num));
		ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
		ArrayList<Integer> temp = new ArrayList<>();
		threeSum(num,0,0,ans,temp);
		return ans;
	}
	public void threeSum(int[] nums, int pos, int target, ArrayList<ArrayList<Integer>> ans,ArrayList<Integer> temp){
		//三个数之和,同理若temp.size()==4表示求4个数之和
		if(temp.size()==3){
			if(target==0){
				//列表需要新建,由于是引用,所以不能直接添加
				ans.add(new ArrayList<>(temp));
			}
			return;
		}
//		可缺省
//		if(pos==nums.length){
//			return;
//		}
		for(int i=pos;i<nums.length;i++){
			temp.add(nums[i]);
			threeSum(nums,i+1,target+nums[i],ans,temp);
			temp.remove(temp.size()-1);
			while((i+1)<nums.length && nums[i]==nums[i+1]){
				i += 1;
			}
		}
	}




#Java开发#
全部评论

相关推荐

不亏是提前批,神仙打架,鼠鼠不配了
站队站对牛:现在92都报工艺岗了
投递韶音科技等公司7个岗位
点赞 评论 收藏
分享
认真搞学习:这么良心的老板真少见
点赞 评论 收藏
分享
05-19 19:57
蚌埠学院 Python
2237:Gpa70不算高,建议只写排名,个人技能不在多而在精,缩到8条以内。项目留一个含金量高的,减少间距弄到一页,硕士简历也就一页,本科不要写很多
实习,投递多份简历没人回...
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-08 14:10
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务