1. 程式人生 > >leetcode 46-Permutation(medium)

leetcode 46-Permutation(medium)

trac num array [] pub lse med continue size

Given a collection of distinct integers, return all possible permutations.

1. count==n, add tinylist to list;

2. iterate through the input array, if the int hasn‘t been added to the tinylist, add it to the tinylist, and continue dbp

class Solution {
    public List<List<Integer>> permute(int
[] nums) { List<List<Integer>> list=new ArrayList<>(); boolean[] bool=new boolean[nums.length]; findPermute(nums, list, new ArrayList<Integer>(), bool); return list; } public void findPermute(int[] nums, List<List<Integer>> list, List<Integer> tinyList, boolean
[] bool){ if(tinyList.size()==nums.length){ list.add(new ArrayList(tinyList)); return; } for(int i=0;i<nums.length;i++){ if(!bool[i]){ bool[i]=true; tinyList.add(nums[i]); findPermute(nums, list, tinyList, bool); bool[i]
=false; tinyList.remove(tinyList.size()-1); } } } }

可以不用bool去存儲tinylist裏是否包含該數字,直接判斷tinylist.contains即可,就是會稍微比用bool存慢一點點,時間換空間

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

註意,在back tracking的時候每次添加tinylist的時候都要新創建一個list加進去,要不然最後加進去的全是空的list!!(

list.add(new ArrayList(tinyList));)

leetcode 46-Permutation(medium)