SHU-2016-SummerPractice / AlgorithmExerciseIssues

算法训练相关文件及工单。
https://github.com/SHU-2016-SummerPractice/AlgorithmExerciseIssues/issues
2 stars 0 forks source link

暴力 2016-08-10 #27

Open zhaokuohaha opened 8 years ago

zhaokuohaha commented 8 years ago

46-全排列: https://leetcode.com/problems/permutations/ 47-高阶全排列: https://leetcode.com/problems/permutations-ii/

zhaokuohaha commented 8 years ago

46 - C# - 递归 - 有点匪夷所思

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

    private void dfs(int[] nums, List<IList<int>> res, List<int> cur)
    {
        if(cur.Count == nums.Length)
        {
            res.Add(cur);
            return;
        }
        for(int i=0; i<nums.Length; i++)
        {
            if (!cur.Contains(nums[i]))
            {
                var newList = new List<int>();
                foreach(var item in cur)
                {
                    newList.Add(item);
                }
                newList.Add(nums[i]);
                dfs(nums, res, newList);
            }
        }
    }
}