leetcode 46 Permutations

題目詳情

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

題目要求咱們對於輸入的數字序列,給出它們的全排列。code

例如,
[1,2,3] 有以下的全排列:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]rem

想法

  • 這道題是用回溯法的思想解決的。
  • 回溯法在包含問題的全部解的解空間樹中,按照深度優先的策略,從根節點出發深度優先搜索,搜索到某個點的時候,先判斷該節點是否包含問題的解,若是包含就繼續探索,不然就逐層向根節點回溯。

解法

public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        
        backtrack(res,new ArrayList<Integer>(),nums);
        
        return res;
    }
    
    public void backtrack(List<List<Integer>> res ,List<Integer> tempList,int[] nums){
        if(tempList.size() == nums.length){
            res.add(new ArrayList<>(tempList));
        }else{
            for(int i=0;i<nums.length;i++){
                if(tempList.contains(nums[i])){
                    continue;
                }
                tempList.add(nums[i]);
                backtrack(res,tempList,nums);
                tempList.remove(tempList.size()-1);
            }
        }
    }
相關文章
相關標籤/搜索