《数据结构、算法与应用》5.(递归输出n个元素的所有子集)

来源:互联网 发布:网络摄像头直播网站 编辑:程序博客网 时间:2024/05/16 06:55

最近在读《数据结构、算法与应用》这本书,把书上的习题总结一下,用自己的方法来实现了这些题,可能在效率,编码等方面存在着很多的问题,也可能是错误的实现,如果大家在看这本书的时候有更优更好的方法来实现,还请大家多多留言交流多多指正,谢谢偷笑吐舌头

 5. 试编写一个递归函数,用来输出n 个元素的所有子集。

     例如,三个元素{a, b, c} 的所有子集是: { }(空集),{ a }, { b }, { c }, { a , b}, { a , c}, {b , c} 和{a , b , c}

////  main.cpp//  Test_05////  Created by cc on 14-3-31.//  Copyright (c) 2014年 cc. All rights reserved.///* 5. 试编写一个递归函数,用来输出n 个元素的所有子集。例如,三个元素{a, b, c} 的所有 子集是: { }(空集),{ a }, { b }, { c }, { a , b}, { a , c}, { b , c} 和{ a , b , c} */#include <iostream>#include "vector"using namespace std;template <typename T>void calcSubSetRecursion(T* array, int lenth, vector<T> subSet);int main(int argc, const char * argv[]) {        int intArray[] = {33, 22, 5};    int arrayLenth = sizeof(intArray) / sizeof(int) ;    vector<int> intVector;    calcSubSetRecursion(intArray, arrayLenth, intVector);    cout << "-----------------------------------" << endl;        char charArray[] = {'a', 'b', 'c'};    int arrayLenth2 = sizeof(charArray) / sizeof(char) ;    vector<char> charVector;    calcSubSetRecursion(charArray, arrayLenth2, charVector);            return 0;}/** *@brief递归输出元素的子集 */template <typename T>void calcSubSetRecursion(T* array, int lenth, vector<T> subSet) {    cout <<"lenth=" << lenth << endl;    if (lenth <= 0) {        cout << "{";        for (int i = 0; i < subSet.size(); i++) {            cout << subSet[i] << ((i == subSet.size() - 1) ? "" : ",");        }        cout << "}" << endl;        return;    }    //将数组的所有元素放入vector    calcSubSetRecursion(array + 1, lenth - 1, subSet);    //当lenth为0时,将{}放入vector    subSet.push_back(array[0]);    calcSubSetRecursion(array + 1, lenth - 1, subSet);}

本文由CC原创总结,如需转载请注明出处:http://blog.csdn.net/oktears/article/details/23610467

0 0
原创粉丝点击