全排列

题目:
给定一个 没有重复 数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]

解题思路:dfs遍历所有决策

class Solution {
    private List<List<Integer>> ans = new ArrayList();
    public List<List<Integer>> permute(int[] nums) {
        LinkedList<Integer> list = new LinkedList();
        dfs(nums, list);
        return ans;
    }
    
    private void dfs(int[] nums, LinkedList<Integer> list) {
        if(nums.length == list.size()) {
            ans.add(new LinkedList(list));
            return ;
        }
        
        for(int num : nums) {
            if(!list.contains(num)) {
                list.add(num);
                dfs(nums, list);
                //撤销之前的选择
                list.removeLast();
            }
        }
    }
}
posted on 2020-11-03 14:27  KobeSacre  阅读(46)  评论(0编辑  收藏  举报