1. 程式人生 > >【兩次過】Lintcode 15. 全排列

【兩次過】Lintcode 15. 全排列

給定一個數字列表,返回其所有可能的排列。

樣例

給出一個列表[1,2,3],其全排列為:

[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

挑戰

使用遞迴和非遞迴分別解決。

注意事項

你可以假設沒有重複數字。

解題思路:

排列DFS問題

public class Solution {
    /*
     * @param nums: A list of integers.
     * @return: A list of permutations.
     */
    public List<List<Integer>> permute(int[] nums) {
        // write your code here
        List<List<Integer>> res = new ArrayList<>();
        if(nums == null)
            return res;
        if(nums.length == 0){
            res.add(new ArrayList<Integer>());
            return res;
        }
            
            
        dfs(nums, new ArrayList<Integer>(), res);
        
        return res;
    }
    
    private void dfs(int[] nums, List<Integer> temp, List<List<Integer>> res){
        if(temp.size() == nums.length)
            res.add(new ArrayList<Integer>(temp));
        
        for(int i=0; i<nums.length; i++){
            if(temp.contains(nums[i]))
                continue;
            
            temp.add(nums[i]);
            dfs(nums, temp, res);
            temp.remove(temp.size()-1);
        }
    }
}