Leetcode 46: Permutations
Given a collection of distinct numbers, return all possible permutations.
For example,[1,2,3] have the following permutations:
[ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]
1 public class Solution { 2 public IList<IList<int>> Permute(int[] nums) { 3 var result = new List<IList<int>>(); 4 DFS(nums, 0, new List<int>(), result); 5 return result; 6 } 7 8 private void DFS(int[] nums, int start, IList<int> result, IList<IList<int>> results) 9 { 10 if (start >= nums.Length) 11 { 12 var r = new List<int>(result); 13 results.Add(r); 14 return; 15 } 16 17 for (int i = start; i < nums.Length; i++) 18 { 19 result.Add(nums[i]); 20 Swap(nums, start, i); 21 DFS(nums, start + 1, result, results); 22 Swap(nums, start, i); 23 result.RemoveAt(result.Count - 1); 24 } 25 } 26 27 private void Swap(int[] nums, int i, int j) 28 { 29 if (i != j) 30 { 31 var tmp = nums[i]; 32 nums[i] = nums[j]; 33 nums[j] = tmp; 34 } 35 } 36 }

浙公网安备 33010602011771号