C++數據結構實驗02--遞歸練習-

#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <windows.h>
using namespace std;


void Out (int * set, int * mark, int size, int c)
{
    if (c == size)
    {
        //結果輸出
        printf ("{");
        for (int i = 0; i < size; i++)
            if (mark[i] == 1)
printf ("%d ", set[i]);

Sleep(500);
        printf ("}\n");
    }
    else
    {
        //確定下標爲c的數字輸出
        mark[c] = 1;
        
        Out (set, mark, size, c + 1);
        
        //確定下標爲c的數字不輸出輸出
        mark[c] = 0;
       
        Out (set, mark, size, c + 1);
    }
}




int _tmain(int argc, _TCHAR* argv[])
{
int set[100];
//用數組mask來判斷是否對元素進行輸出,它的值只有0和1
    int mark[100];
printf("Input\n");  
    int myInput;  
    int i=0;  
    while(true){  
        cin>>myInput;  
        if (myInput==0){  
           
            break ;  
        }else{  
            set[i] =myInput;  
        }  
        i++;  
    }  
    printf("Output\n");  
    
Out (set, mark, i, 0);
    
    return 0;




}









#include "stdafx.h"
#include<iostream> 
#include<windows.h>
using namespace std;
template<class T>  
void Perm(T list[], int k , int m){  
    if (k== m){  
        for (int i = 0; i<=m;i++){  
            if(i!=m)  //判斷是不是數組輸出的最後一個
                cout<<list[i]<<",";  
            if(i==m)  
                cout<<list[i];  
        }  
    cout<<endl;  
    }else{   
        for(int i=k; i<=m;i++){  
            Swap(list[k],list[i]);  
            Perm(list, k+1,m);  
            Swap(list[k],list[i]); 
Sleep(500);
        }  
    }  
}  
//交換兩個數
template <class T>  
inline void Swap(T& a, T& b){  
    T temp = a;  
    a = b;   
    b = temp;  
}  
  




int _tmain(int argc, _TCHAR* argv[])
{
int list[10];  
    int length = 1;  
    printf("Input\n");  
    int myInput;  
    int i=0;  
    while(true){  
        cin>>myInput;  
        if (myInput==0){  
            i--;  
            break ;  
        }else{  
            list[i] =myInput;  
        }  
        i++;  
    }  
    printf("Output\n");  
    Perm(list,0,i); 

return 0;
}


發佈了27 篇原創文章 · 獲贊 9 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章