aboutsummaryrefslogtreecommitdiff
path: root/Computer_Science/leetcode/15-3_sum.c
diff options
context:
space:
mode:
authorSteve Lee <me@xiangyangli.com>2018-01-13 05:13:14 +0800
committerSteve Lee <me@xiangyangli.com>2018-01-13 05:13:14 +0800
commita46ec300092c1ee8ccac629b7f335643f87662f5 (patch)
treeb03e20d905e6f583df626386164daf4aa5f81519 /Computer_Science/leetcode/15-3_sum.c
parent79a9c52fa923fc78074d88463449a8b7f95ca3ef (diff)
download42-a46ec300092c1ee8ccac629b7f335643f87662f5.tar.xz
42-a46ec300092c1ee8ccac629b7f335643f87662f5.zip
update
Diffstat (limited to 'Computer_Science/leetcode/15-3_sum.c')
-rw-r--r--Computer_Science/leetcode/15-3_sum.c37
1 files changed, 37 insertions, 0 deletions
diff --git a/Computer_Science/leetcode/15-3_sum.c b/Computer_Science/leetcode/15-3_sum.c
new file mode 100644
index 0000000..cb60873
--- /dev/null
+++ b/Computer_Science/leetcode/15-3_sum.c
@@ -0,0 +1,37 @@
+/**
+ * Return an array of arrays of size *returnSize.
+ * Note: The returned array must be malloced, assume caller calls free().
+ */
+void helper(int **result, int *nums, int start, int numsSize, int *tmp, int count, int *returnSize)
+{
+ if(start >= numsSize) return;
+ if(count < 3) {
+ tmp[count] = nums[start];
+ helper(result, nums, start + 1, numsSize, tmp, count + 1, returnSize);
+ }
+ else if(count == 3) {
+ if(tmp[0] + tmp[1] + tmp[2] == 0) {
+ *(result + *returnSize) = malloc(sizeof(int) * 3);
+ **(result + *returnSize) = tmp[0];
+ *(*(result + *returnSize) + 1) = tmp[1];
+ *(*(result + *returnSize) + 2) = tmp[2];
+ ++*returnSize;
+ }
+ helper(result, nums, start, numsSize, tmp, count - 1, returnSize);
+ helper(result, nums, start, numsSize, tmp, count - 2, returnSize);
+ }
+
+}
+
+int** threeSum(int* nums, int numsSize, int* returnSize) {
+ *returnSize = 0;
+ int **result = malloc(sizeof(int *) * 100);
+ int tmp[3];
+ int count = 0;
+
+ for(int i = 0; i < numsSize; i++) {
+ helper(result, nums, i, numsSize, tmp, 0, returnSize);
+ }
+
+ return result;
+}