P1706 全排列问题(DFS/自带函数)

 题目传送门

题目意思很明显,这里便不做解释了

思路分析1:

考虑DFS

可以作一个模拟,模拟将1到n这n个数字放到n个箱子的问题,用一个vector作为箱子,

对于每一个箱子,都有n种可能性(因为有n个数字),因此每一次递归都需要循环遍历n个数字,同时我们还需要记录下每一个数字是否被使用过,递归终点就是所有箱子都放满了 

#include<iostream>
#include<vector>

using namespace std;

int n;
vector<int>temp;
vector<bool>visited;

void dfs(int index) {//index代表箱子编号
	if (index == n) {
		for (int i = 0; i < n; i++) {
			cout << "    " << temp[i];//输出所有箱子数字
		}
		cout << endl;
	}
	else {
		for (int i = 1; i <= n; i++) {
			if (!visited[i]) {
				visited[i] = true;
				temp.push_back(i);
				dfs(index + 1);
				temp.pop_back();//回溯时记得恢复原状
				visited[i] = false;
			}
		}
	}
}

int main()
{
	cin >> n;
	for (int i = 1; i <= n + 1; i++) {
		visited.push_back(false);
	}//初始化
	dfs(0);
	return 0;
}

 思路2:

如果你足够“见多识广”的话,应该知道在algorithm头文件里存在两个全排列函数

知识传送门

具体了解可以进入上面链接

这里直接给代码

#include <iostream>  
#include <algorithm>  
using namespace std;
int main()
{
    int n;
    cin >> n;
    int* arr = new int[n];
    for (int i = 0; i < n; i++) {
        arr[i] = i+1;
    }
    do
    {
        for (int i = 0; i < n; i++) {
            cout << "    " << arr[i];
        }
        cout << endl;
    } while (next_permutation(arr, arr + n));
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZZZWWWFFF_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值