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

For example,
[1,2,3] have the following permutations:

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

一直困惑dfs和回溯到底有什么区别,感觉回溯就是dfs,dfs就是回溯=。=,你不回溯你怎么dfs,你不dfs怎么去回溯。。。
可能用途不一样吧。。。
public class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res=new ArrayList<>();
        if(nums==null||nums.length==0)
        {
            return res;
        }
        Arrays.sort(nums);
        List<Integer> list=new ArrayList<Integer>();
        helper(res,list,nums);
        return res;
    }
    private void helper(List<List<Integer>> res, List<Integer> list, int[] nums)
    {
        if(list.size()==nums.length)
        {
            res.add(new ArrayList<Integer>(list));
            return;
        }
        for(int i=0;i<nums.length;i++)
        {
            if(list.contains(nums[i]))
            {
                continue;
            }
            list.add(nums[i]);
            helper(res,list,nums);
            list.remove(list.size()-1);
        }
    }
}

 

Difference:
REF:http://stackoverflow.com/questions/1294720/whats-the-difference-between-backtracking-and-depth-first-search
这个解释的很好.回溯是一种思想,而dfs只应用于遍历树或者搜索树/图结构,dfs是一种实现回溯的算法。

   Backtracking is a more general purpose algorithm.

  Depth-First search is a specific form of backtracking related to searching tree structures 


dfs定义:https://en.wikipedia.org/wiki/Depth-first_search
backtracking定义:https://en.wikipedia.org/wiki/Backtracking

这样理解的话,这道题就是用dfs的模型也就是tree的模型来做,同时也应用了其中回溯的思想。绕死我了(:

posted on 2016-09-14 16:39  Machelsky  阅读(128)  评论(0)    收藏  举报