Here order is not important, so don’t print the duplicated combination.
e.g. target is 7, candidate is 2,3,6,7
output should be 7 and 3+2+2 (but not print 2+3+2, 2+2+3
My Attempt
void Sum(int arr[], int reminder, int index, int visited[]) {
if (index LessThen 0) { return }
if (difference == 0) { printSum(arr, visited) , return; }
if (reminder - arr[index] LessThen 0) { return }
visited[index]++;
Sum(arr, reminder - arr[index] , index, visited) // duplicate number
Sum(arr, reminder - arr[index], index - 1, visited) // next number
visted[index]--;
Sum(arr, reminder, index - 1, visited) // skip
}
Find all possible combination of numbers using a pre-defined candidate set.
Each number from the candidate set may be used only once in the combination.
For example,
Candidate Set = {10, 1, 2, 7, 6, 1, 5}
Target Number = 8
One possible output could be:
1+1+6
1+2+5
1+7
2+6
e.g. target is 7, candidate is 2,3,6,7
output should be 7 and 3+2+2 (but not print 2+3+2, 2+2+3e.g. target is 7, candidate is 2,3,6,7
output should be 7 and 3+2+2 (but not print 2+3+2, 2+2+3e.g. target is 7, candidate is 2,3,6,7
output should be 7 and 3+2+2 (but not print 2+3+2, 2+2+3
// repeat the current index for possible duplicates
}
No comments:
Post a Comment