数组的组合和全排列

经典面试题:

a)求一个全排列函数:如p([1,2,3]) ,输出:  [123],[132],[213],[231],[321],[323]。
b)求一个组合函数:    如p([1,2,3]) ,输出:[1],[2],[3],[1,2],[2,3],[1,3],[1,2,3]。

对于组合和排列问题拿递归做是很方便的,下面给出代码:

 

#include <cstdlib>
#include <string.h>
#include <iostream>
#include <stdio.h>
using namespace std;
void theWholeArray(int arr[], int n, int index, string p)
{
     char buff[16];
     int tmp;
     if(index == n)
     {
              cout<<p<<endl;
              return;
     }
     for(int i = 0; i < n; i++)
     {
             if(arr[i] != -1)
             {
                       sprintf(buff, "%d", arr[i]);
                       tmp = arr[i];
                       arr[i] = -1;
                       theWholeArray(arr, n, index + 1, p + buff);
                       arr[i] = tmp;
                       
                       
             }
     }
     
     
}

void theComArray(int arr[], int n, int index, string p)
{
     char buff[16];
     if(index == n)
     {
              if(p != "")
                   cout<<p<<endl;
              return;
     }     
    
     sprintf(buff, "%d", arr[index]);
     theComArray(arr, n, index + 1, p + buff);
     theComArray(arr, n, index + 1, p + "");
     
}
int main()
{
        int arr[] = {1,2,3};
        theWholeArray(arr, 3, 0, "");
        
        return 0;
}    


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值