用visited数组标记要输出即可,当dfs到达边界,遍历数组输出即可
#include <iostream>
using namespace std;
int visited[20] = {0};
int arr[20];
int n;
void dfs(int nums, int begin, int cur_nums)
{
if (cur_nums==nums)
{
for(int i = 1; i<=n;i++)
{
if(visited[i] == 1)
cout << i <<" ";
}
cout << endl;
return;
}
for(int i = begin;i<=n;i++)
{
if(visited[i] == 0)
{
visited[i] = 1;
dfs(nums, i+1, cur_nums+1); // 不要用i++和cur_nums++
visited[i] = 0;
}
}
}
int main(){
cout <<endl;
cin >>n;
for(int i=1;i<=n;i++)
dfs(i, 1, 0);
}