程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> LeetCode 18: 4Sum

LeetCode 18: 4Sum

編輯:C++入門知識

LeetCode 18: 4Sum


Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, abcd)The solution set must not contain duplicate quadruplets.
    For example, given array S = {1 0 -1 0 -2 2}, and target = 0.

    A solution set is:
    (-1,  0, 0, 1)
    (-2, -1, 1, 2)
    (-2,  0, 0, 2)


代碼如下:

class Solution {
public:
    vector > fourSum(vector &num, int target) {
		vector> out;
		set> res;
		if (num.size() < 4)
			return out;
		sort(num.begin(), num.end());
		for (int i=0; i tmp;
						tmp.push_back(num[i]);
						tmp.push_back(num[j]);
						tmp.push_back(num[begin]);
						tmp.push_back(num[end]);
						res.insert(tmp);
						begin++;
						end--;
					} 
					else if(sum < target)
					{
						begin++;
					}else{
						end--;
					}
				}
				
			}
		}
		 set>::iterator it = res.begin();  
        for(; it != res.end(); it++)  
            out.push_back(*it); 


	}
};


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved