不錯的問題:-)
我不會發布我的完整解決方案,因爲問題似乎是功課。就在幾個三分球......
我用遞歸解決它:我使用的簡化過程是發現target
在n
陣列的總和一樣n-1
陣列發現的target - ONE_ELEMENT
的總和。
使用3個陣列和零
find 3 elements with sum 0 in {2, 1, 4, 7}, {3, -3, -8, 0}, {-1, -4, -7, 6}
find 2 elements with sum 0 - 2 (-2) in {3, -3, -8, 0}, {-1, -4, -7, 6}
find 1 elements with sum -2 - 3 (-5) in {-1, -4, -7, 6} NOT FOUND
find 1 elements with sum -2 - -3 (1) in {-1, -4, -7, 6} NOT FOUND
find 1 elements with sum -2 - -8 (6) in {-1, -4, -7, 6} YAY! FOUND
...
目標爲了讓工作輕鬆
例子,我有創造的數組中的數據結構,並想出了一個辦法來傳遞信息在遞歸函數的幾次調用之間(我使用了輔助遞歸設置函數中分配的另一個數組)。
爲陣列結構是
struct sizedarray {
int *data;
size_t nelems;
};
和用於遞歸和輔助函數的原型是
findtarget(int target, struct sizedarray *arrays, size_t narrays);
findtarget_recursive(int target, struct sizedarray *arrays, size_t narrays, size_t level, int *saved);
編輯補充的工作溶液
#include <stdio.h>
#include <stdlib.h>
/* struct to hold arrays with varying sizes */
struct sizedarray {
int *data;
size_t nelems;
};
void findtarget_recursive(int target,
struct sizedarray *arrays,
size_t narrays,
size_t level,
int *saved) {
size_t k, j;
struct sizedarray *curarray = arrays + level;
/* if no arrays left to search return */
if (level == narrays) {
return;
}
/* if only 1 arrays do not recurse */
if (level + 1 == narrays) {
for (k = 0; k < curarray->nelems; k++) {
if (curarray->data[k] == target) {
/* print saved elements from previous arrays */
for (j = 0; j < level; j++) {
printf("%d ", saved[j]);
}
/* print current element from current array */
printf("%d\n", curarray->data[k]);
}
}
return;
} else {
/* when 2 or more arrays left, recurse */
for (k = 0; k < curarray->nelems; k++) {
saved[level] = curarray->data[k];
findtarget_recursive(target - curarray->data[k],
arrays,
narrays,
level + 1,
saved);
}
}
}
int findtarget(int target, struct sizedarray *arrays, size_t narrays) {
int *saved = NULL;
saved = malloc(narrays * sizeof *saved);
/* assume it worked, needs something when it fails */
if (saved) {
findtarget_recursive(target, arrays, narrays, 0, saved);
free(saved);
}
return 0;
}
int main(void) {
int a0[] = {2, 1, 4, 7};
int a1[] = {3, -3, -8, 0};
int a2[] = {-1, -4, -7, 6};
int a3[] = {1, 5, 6, 7};
int a4[] = {-10, -4, -1, 3, 8};
int a5[] = {17, 18, 19, 20, 21, 22, 23, 24, 25};
struct sizedarray arrays[6];
int target = 0;
arrays[0].data = a0; arrays[0].nelems = sizeof a0/sizeof *a0;
arrays[1].data = a1; arrays[1].nelems = sizeof a1/sizeof *a1;
arrays[2].data = a2; arrays[2].nelems = sizeof a2/sizeof *a2;
findtarget(target, arrays, 3);
arrays[3].data = a3; arrays[3].nelems = sizeof a3/sizeof *a3;
arrays[4].data = a4; arrays[4].nelems = sizeof a4/sizeof *a4;
arrays[5].data = a5; arrays[5].nelems = sizeof a5/sizeof *a5;
puts("\n\nwith 6 arrays ...");
findtarget(target, arrays, 6);
return 0;
}
莫非你讓你的問題更清楚?你究竟在問什麼? – 2011-04-26 05:39:43
問題是什麼? – JeremyP 2011-04-26 07:11:34
我有6個表格,我將它們放入一個2維數組中。我會在這裏提供一個值爲10的值,比如val = 0。我需要從這些表中搜索組成10的所有組合值。價值將從所有這些表中的值計算。我希望現在清楚。 – Sumanth 2011-04-26 09:31:03