51Nod 2152 数字组合 c/c++题解

题目描述

现在小瓜有1到n这n个整数,他想知道用这n个整数组成一个长度为n的数字序列的所有方法(每个整数可以重复使用)。你能帮助他吗?
输入
一行一个整数n(1<=n<=6)。
输出
若干行,每行表示用1到n组成一个长度为n的数字序列的一种方法。所有方法按字典许输出。
输入样例
2
输出样例
1 1
1 2
2 1
2 2

题解:

直接用dfs枚举出所有的情况即可,看代码。

代码:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll  INF = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double E = exp(1.0);
const int MOD = 1e9+7;
const int MAX = 1e5+5;
int n;
int a[6+5];

void dfs(int i)
{
    if(i == n)
    {
        for(int j = 0; j < n; j++)
            cout << a[j] << " ";
        cout << endl;
        return;
    }
    for(int k = 1; k <= n; k++)
    {
        a[i] = k;
        dfs(i+1);
    }
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    while(cin >> n)
    {
        dfs(0);
    }

    return 0;
}

你可能感兴趣的:(#,51Nod,51Nod算法题解,dfs)