Leetcode46——Permutations

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. 问题描述

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]
]

2. 求解

递归法

这道题是求数组的全排列,首先可以用递归法,第一次往链表添加一个元素,有n中可能,然后将剩下的元素再添加一个元素到链表中,有n-1种可能,以此类推,直至链表中的元素大小等于数组大小。

public class Solution {
    public static List<List<Integer>> result = new ArrayList<List<Integer>>();
    public List<List<Integer>> permute(int[] nums) {
        result.clear();
        permutation(nums, new ArrayList());
        return result;
    }
    public void permutation(int[] nums, List<Integer> list) {
        if(list.size() == nums.length) {
            result.add(list);
            return;
        }
        for(int i = 0; i < nums.length; i++) {
            if(!list.contains(nums[i])) {
                List<Integer> subList = new ArrayList<Integer>(list);
                subList.add(nums[i]);
                permutation(nums, subList);
            }
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 46. Permutations Given a collection of distinct numbers, ...
    LdpcII阅读 2,669评论 0 0
  • LeetCode 刷题随手记 - 第一部分 前 256 题(非会员),仅算法题,的吐槽 https://leetc...
    蕾娜漢默阅读 18,181评论 2 36
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,357评论 0 33
  • 1、每个程序所花费的运行次数称为该程序的“时间复杂度”。判断该程序执行效率是否良好。 2、 3、内存的位置: 以行...
    EdwardSelf阅读 4,183评论 0 1
  • 9.3.3 快速排序   快速排序将原数组划分为两个子数组,第一个子数组中元素小于等于某个边界值,第二个子数组中的...
    RichardJieChen阅读 5,840评论 0 3

友情链接更多精彩内容