section and Problem algorithm code (C)

Source: Internet
Author: User
Tags printf

Title: Given integer a1, A2, ..., an, to determine whether a number can be selected from it, so that their and exactly k.

There are many solutions, the simplest solution is to use depth first search, time complexity O (2^n), not the optimal solution.

Code:

* * * * * main.cpp * * *  Created on:2014.7.13 * 
 This column more wonderful content: http://www.bianceng.cnhttp:// www.bianceng.cn/Programming/sjjg/
 *      author:spike 
 /
      
/*eclipse CDT, gcc 4.8.1*/
      
#include < stdio.h>  
      
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\n");  
    else printf ("no\n");  
}  
      
      
int main (void)  
{  
    const int max_n =;  
    int A[max_n] = {1, 2, 4, 7};  
    int n = 4, k = 13; K-bit need to find the number  
      
    solve (A, n, k);  
      
    return 0;  
}

Output:

Yes

Author: csdn Blog Mystra

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.