HDU 1521 排列组合 搜索

排列组合

Problem Description
有n种物品,并且知道每种物品的数量。要求从中选出m件物品的排列数。例如有两种物品A,B,并且数量都是1,从中选2件物品,则排列有"AB","BA"两种。
 
Input
每组输入数据有两行,第一行是二个数n,m(1<=m,n<=10),表示物品数,第二行有n个数,分别表示这n件物品的数量。
 
Output
对应每组数据输出排列数。(任何运算不会超出2^31的范围)
 
Sample Input
2 2 1 1
 
Sample Output
2

 AC代码

#include<bits/stdc++.h>
using namespace std;
int n,m,s,a[11];
void dfs(int x){
    if(x==0){
        s++;return;
    }
    for(int i=0;i<n;++i){
        if(a[i]){
            a[i]--;
            dfs(x-1);
            a[i]++;
        }
    }
}
int main(){
    while(cin>>n>>m)
    {
        s=0;
        for(int i=0;i<n;i++)
        {
            scanf("%d",&a[i]);
        }
        dfs(m);
        cout<<s<<endl;
    }
    return 0;
}

dfs  如果只要求找到解,不需要回溯

如果需要找出所有解则需要

原文地址:https://www.cnblogs.com/m2364532/p/12331210.html