Leetcode 46. Permutations

来源:互联网 发布:知乎b站三国演义 编辑:程序博客网 时间:2024/06/08 08:12
/** * e.g. nums = 1, 2, 3 * bt() *   tmp(1) *   bt() *     tmp(1, 2) *   bt() *     tmp(1, 2, 3) *     bt() *      add(tmp) return *     tmp.remove(2) *     i == 2 end return *   remove(1) *   i == 1 tmp(1, 3) *   bt() *     tmp(1, 3, 2) *     bt() *      add(tmp) return *   ... */ public class Solution {    public static void backTrack(int[] nums, List<Integer> tmp, List<List<Integer>> res) {        if (tmp.size() == nums.length) {            res.add(new ArrayList<>(tmp));            return;        }        else {            for (int i=0; i<nums.length; i++) {                if (tmp.contains(nums[i])) continue;        // time complexity for ArrayList.contains is O(n)                tmp.add(nums[i]);                backTrack(nums, tmp, res);                tmp.remove(tmp.size()-1);            }        }    }        public List<List<Integer>> permute(int[] nums) {        List<List<Integer>> res = new ArrayList<>();        backTrack(nums, new ArrayList<>(), res);        return res;    }}

0 0
原创粉丝点击