public class Solution {
    public IList<IList<int>> Permute(int[] nums)
        {
            IList<IList<int>> result = new List<IList<int>>();
            permute(result, nums, 0);
            return result;
        }

        private void permute(IList<IList<int>> result, int[] array, int start)
        {
            if (start >= array.Length)
            {
                List<int> current = new List<int>();
                foreach (int a in array)
                {
                    current.Add(a);
                }
                result.Add(current);
            }
            else
            {
                for (int i = start; i < array.Length; i++)
                {
                    swap(array, start, i);
                    permute(result, array, start + 1);
                    swap(array, start, i);
                }
            }
        }

        private void swap(int[] array, int i, int j)
        {
            int temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
}

https://leetcode.com/problems/permutations/#/solutions

经过学习和思考,采用另一种写法实现。更容易理解

public class Solution
    {
        List<IList<int>> list = new List<IList<int>>();
        int N;
        private void BackTrack(List<int> records, List<int> save, int t)
        {
            if (t >= N)
            {
                var temp = new int[N];
                save.CopyTo(temp);
                list.Add(temp.ToList());
                return;
            }

            for (int i = 0; i < records.Count; i++)
            {
                var current = records[i];
                save.Add(current);
                var notsave = records.Where(x => x != current).ToList();
                BackTrack(notsave, save, t + 1);
                save.Remove(current);
            }
        }

        public IList<IList<int>> Permute(int[] nums)
        {
            N = nums.Length;//初始化最大范围
            var records = nums.ToList();
            var save = new List<int>();
            BackTrack(records, save, 0);
            return list;
        }
    }

 

补充一个python的实现:

 1 class Solution:
 2     def dfs(self,nums,n,path,l,visited):
 3         if len(path) == n:
 4             l.append(path[:])
 5         else:
 6             if nums != None:
 7                 for i in range(len(nums)):
 8                     if visited[i] == 1:
 9                         continue
10                     path.append(nums[i])
11                     visited[i] = 1
12                     self.dfs(nums,n,path,l,visited)
13                     visited[i] = 0
14                     path.pop(-1)
15             
16         
17     def permute(self, nums: 'List[int]') -> 'List[List[int]]':
18         n = len(nums)
19         path = list()
20         l = list()
21         visited = [0] * n
22         self.dfs(nums,n,path,l,visited)
23         return l

 

posted on 2017-06-09 09:01  Sempron2800+  阅读(188)  评论(0编辑  收藏  举报