c ++ full array problem

Title Description

Arrangement, generally removed from the n different elements m (m≤n) elements, arranged in accordance with a certain order, called out a permutation of m elements (Arrangement) from the n elements. In particular, when m = n, this arrangement is referred to as a full permutation (Permutation).

Presented to a positive integer (1 <= n <= 8), the output of all the whole arrangement.

For example n = 3, the output of all combinations, and outputs the lexicographical ordering:

1 2 3

1 3 2

2 1 3

2 3 1

3 1 2

3 2 1

Each full array row, adjacent two numbers separated by a space (the last number is not followed by a space)

Entry

Enter an integer n

Export

The output of all the whole arrangement, each arrangement per line, between the two numbers separated by a space the same arrangement.

Sample input

3

Sample Output

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

Source Code

#include <iostream>//头文件
#include <string.h>//
using namespace std;//
bool used[10];//这个组合曾经有过(是否重复)
int ans[10];//排列出来的数
int n;//
void dfs(int u)//dfs函数
{
    if(u == n + 1)//如果满足3个数据,则输出
    {
        for (int i = 1;i <= n;i ++)//
            printf("%d ",ans[i]);//ans[i]就是输出数据里面的第i个
        printf("\n");
        return ;    
    }
    for (int i = 1;i <= n;i ++)
        if(used[i] == 0)//如果i没有被选中
        {
            ans[u] = i;//如果没有被选中,就把i放到ans[]中
            used[i] = 1;//used[2] = 1表示2这个数已经被选过了  used[3] = 1表示3这个数已经被选过了
            dfs(u + 1);//继续选下一个数字  dfs(1):选第1个数  dfs(2):选第2个数  dfs(n + 1):打印,退出
            used[i] = 0;//打印完毕,把该数字取消
        }
}
int main()
{
    memset(used,0,sizeof(used));
    cin >> n;
    dfs(1);
    return 0;
}

Guess you like

Origin www.cnblogs.com/LJA001162/p/11334902.html