046 Permutations

Given a collection of distinct integers, return all possible permutations.

Example:

Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]

解释下题目:

输出全排列喽

1. 递归调用呗

实际耗时:3ms

public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        recursion(result, new ArrayList<>(), nums);
        return result;
    }

    private void recursion(List<List<Integer>> list, List<Integer> tempList, int[] nums) {
        if (tempList.size() == nums.length) {
            list.add(new ArrayList<>(tempList));
        } else {
            for (int i = 0; i < nums.length; i++) {
                if (tempList.contains(nums[i])) {
                    //如果已经存在了,则不需要再遍历了
                    continue;
                }
                tempList.add(nums[i]);
                recursion(list, tempList, nums);
                tempList.remove(tempList.size() - 1);
            }
        }
    }

  就是一个全排列,先把第一个加进来,然后不断加东西进来,如果长度等于数组的长度,说明找到一个解了,否则就继续深入,唯一值得注意的点就是需要判断这个数字有没有出现过而已。

时间复杂度O(n!)
空间复杂度O(n!)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • <center>#1 Two Sum</center> link Description:Given an arr...
    铛铛铛clark阅读 2,203评论 0 3
  • 三、RSA scalabilityRSA可扩展性 Obviously a post-quantum RSA pub...
    jorson2000阅读 578评论 0 0
  • 刚刚看完了卡勒德·胡塞尼的《追风筝的人》,很喜欢也很感动也很唏嘘不已。喀布尔、巴米扬、塔列班这些关于阿富汗...
    micky夕木阅读 235评论 0 2
  • 文/刘玥彤 1 杏花城之所以叫杏花城,只是因为杏花坡上那棵巨大的杏花树,一到春天,满树的粉红色把整片天空都...
    远方文团阅读 472评论 0 1
  • 或许在这个世界上,无论做什么,都会顾此失彼吧。 某天,他一夜之间收敛了所有的年少戾气,眼神里尽是温柔,仿佛脱胎换骨...
    笔随康小白阅读 218评论 0 0