Programming Algorithm-part and question code (C)

Source: Internet
Author: User

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


 

 

 

 

 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.