GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — coding-problems/Other/permutations.py at master · Pranshu-Raj/coding-problems Expand file tree/ Copy pathpermutations.pyMore file actions 58 lines (44 loc) · 1.18 KB / Copy pathpermutations.pyFile metadata and controls58 lines (44 loc) · 1.18 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 ''' Permutations Given a collection of distinct integers, return all possible permutations. Input: [1,2,3] Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ] ========================================= A classical recursive algorithm for permutations. Time Complexity: O(N!) Space Complexity: O(N!) ''' ############ # Solution # ############ def permutations(nums): result = [] if len(nums) == 0: return result permute(result, set(nums), []) return result def permute(result, nums, permutation): if len(nums) == 0: result.append([num for num in permutation]) else: for num in list(nums): # create a new object with the same values because nums will be changed later nums.remove(num) permutation.append(num) permute(result, nums, permutation) # reset the structures del permutation[-1] nums.add(num) ########### # Testing # ########### # Test 1 # Correct result => [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] print(permutations([1, 2, 3])) |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |