Permutations(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], and [3,2,1].

思路: 典型的backtracking,注意list在递归的过程一直在变化,所以每次加入的list需要重新创建。result.add(new ArrayList(list));

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

public class Solution {
    public List> permute(int[] nums) {
        List> result = new ArrayList>();
        List list = new ArrayList();
        helper(result, list, nums);
        return result;
    }
    private void helper(List> result, List list, int[] nums) {
        if (list.size() == nums.length) {
            if (!result.contains(list)) {
                result.add(new ArrayList(list));
                return;
            }
        }
        for (int i = 0; i < nums.length; i++) {
            if (list.contains(nums[i])) {
                continue;
            }
            list.add(nums[i]);
            helper(result,list,nums);
            list.remove(list.size() - 1);
        }
    }
}

关键字:list, nums, result, arraylist

版权声明

本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处。如若内容有涉嫌抄袭侵权/违法违规/事实不符,请点击 举报 进行投诉反馈!

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部