[LeetCode-Java]46. Permutations

来源:互联网 发布:nw.js electron 编辑:程序博客网 时间:2024/06/06 12:35

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

解1:使用递归,每次添加不重复的数,添加满则加入到结果集中。9ms。

public class Solution {     List<List<Integer>> result = null;    public List<List<Integer>> permute(int[] nums) {        if (nums == null || nums.length == 0)  return result;        result = new ArrayList<>();        dfs(nums,0,new ArrayList<Integer>());        return result;    }    void dfs(int[] nums, int start, List<Integer> list){        if (start == nums.length) {            result.add(new ArrayList<Integer>(list));            return;        }        for (int i = 0;i<nums.length;i++){            if (!list.contains(nums[i])) {                list.add(nums[i]);                dfs(nums, start + 1, list);                list.remove(list.size()-1);            }        }    }}
0 0
原创粉丝点击