Advertisement
d_brezoev

GetAllPermutations

Dec 18th, 2013
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.22 KB | None | 0 0
  1. //* Write a program that reads a number N and generates and prints all the permutations of the numbers [1 … N]. Example:
  2. //      n = 3  {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2}, {3, 2, 1}
  3. using System;
  4. using System.Collections.Generic;
  5. class Permutations
  6. {    
  7.     static void Print(int[] arr)
  8.     {
  9.         for (int i = 0; i < arr.Length; i++)
  10.         {
  11.             Console.Write(arr[i]+" ");
  12.         }
  13.         Console.WriteLine();
  14.     }
  15.     static void Permute(int[] arr, int index,List<int> list)
  16.     {        
  17.         if (index == arr.Length)
  18.         {
  19.             Print(arr);            
  20.         }
  21.         else
  22.         {
  23.             for (int i = 1; i < arr.Length+1; i++)
  24.             {
  25.                 if (list.Contains(i))
  26.                 {
  27.                     continue;
  28.                 }
  29.                 arr[index] = i;
  30.                 list.Add(i);
  31.                 Permute(arr, index + 1, list);
  32.                 list.Remove(i);
  33.             }            
  34.         }      
  35.     }
  36.     static void Main()
  37.     {
  38.         int n = int.Parse(Console.ReadLine());
  39.         int[] arr = new int[n];
  40.         List<int> list = new List<int>();
  41.         Permute(arr, 0, list);        
  42.     }        
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement