Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //* Write a program that reads a number N and generates and prints all the permutations of the numbers [1 … N]. Example:
- // n = 3 {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2}, {3, 2, 1}
- using System;
- using System.Collections.Generic;
- class Permutations
- {
- static void Print(int[] arr)
- {
- for (int i = 0; i < arr.Length; i++)
- {
- Console.Write(arr[i]+" ");
- }
- Console.WriteLine();
- }
- static void Permute(int[] arr, int index,List<int> list)
- {
- if (index == arr.Length)
- {
- Print(arr);
- }
- else
- {
- for (int i = 1; i < arr.Length+1; i++)
- {
- if (list.Contains(i))
- {
- continue;
- }
- arr[index] = i;
- list.Add(i);
- Permute(arr, index + 1, list);
- list.Remove(i);
- }
- }
- }
- static void Main()
- {
- int n = int.Parse(Console.ReadLine());
- int[] arr = new int[n];
- List<int> list = new List<int>();
- Permute(arr, 0, list);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement