leetcode 46. Permutations

思路一:迭代法

class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> ans = new LinkedList<>();
        
        List<Integer> l = new LinkedList<>();
        if (nums.length == 0) {
            ans.add(l);
            return ans;
        }
        l.add(nums[0]);
        ans.add(l);
        for(int i = 1; i < nums.length; i++) {
            int len = ans.size();
            while (len -- > 0) {
                List<Integer> list = ans.get(0); //第一個List<Integer>
                ans.remove(0); //彈出第一個List元素,在該List中插入下一個數;
                int count = list.size(); //插空法,長度爲count的list,
                                            //新插入一個數,有count+1中插法
                for (int j = 0; j <= count; j++) {
                    ans.add(insert(list, j, nums[i])); //插入數後,將新的list加入ans中
                }
            }
        }
        return ans;
    }
    //將value插入list中的index處,生成一個新的list
    public List<Integer> insert(List<Integer> list, int index, int val) {
        List<Integer> l = new LinkedList<>();
        l.addAll(list);
        l.add(index, val);
        return l;
    }
}

思路二:回溯法

public List<List<Integer>> permute(int[] nums) {
   List<List<Integer>> list = new ArrayList<>();
   backtrack(list, new ArrayList<>(), nums);
   return list;
}

private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums){
   if(tempList.size() == nums.length){
      list.add(new ArrayList<>(tempList));
   } else{
      for(int i = 0; i < nums.length; i++){ 
         if(tempList.contains(nums[i])) continue; // element already exists, skip
         tempList.add(nums[i]);
         backtrack(list, tempList, nums);
         tempList.remove(tempList.size() - 1);
      }
   }
} 

 

發佈了49 篇原創文章 · 獲贊 15 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章