Programming Algorithm-part and question code (C)
Part and question code (C)
Question: Given integers a1, a2,..., an, can be used to determine whether a number of numbers can be selected to make the sum of them exactly k.
There are many solutions. The simplest solution is to useDeep Priority Search,Time complexity O (2 ^ n),Not optimalSolution.
Code:
/** Main. cpp ** Created on: 2014.7.13 * Author: Spike * // * eclipse cdt, gcc 4.8.1 */# include
Bool dfs (int I, int sum, int * a, int n, int k) {if (I = n) return sum = k; if (dfs (I + 1, sum, a, n, k) return true; if (dfs (I + 1, sum + a [I], a, n, k) return true; return false;} void solve (int * a, int n, int k) {if (dfs (0, 0, a, n, k )) printf (Yes); else printf (No);} int main (void) {const int MAX_N = 20; int a [MAX_N] = {1, 2, 4, 7 }; int n = 4, k = 13; // The number solve (a, n, k) to be found in the k-bit; return 0 ;}
Output:
Yes