46. Permutations

2020/01/09 Leetcode

46. Permutations

Tags: ‘Backtracking’

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

Solution

经典的Backtrack问题,参考 https://www.v2ex.com/t/633719#reply0

方法1:模板 92%,里面有些方法效率很低,比如LinkedList contains() ,

class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> result  = new LinkedList<>();
        backtrack(nums, new LinkedList<Integer>(), result);
        return result;
    }
    
    private void backtrack(int[] nums, LinkedList<Integer> track, List<List<Integer>> result) {
        // termination
        if (track.size() == nums.length ) {
            result.add(new LinkedList(track));
            return;
        }
        
        for (int i = 0; i < nums.length; i++) {
            // 剪枝
            if (track.contains(nums[i])) {
                continue;
            }
            track.add(nums[i]); // 做选择
            backtrack(nums, track, result); // 进入下一层决策树
            track.removeLast(); // 取消选择
        }
    }
}

Search

    Table of Contents