46. Permutations

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]
]



求一个数组的所有排列 挺简单一道题 结果迅速写出了组合 不知道怎么回溯。。。

以下是top vote 

回溯其实很简单 就是把最后添加的元素删除 后续再添加 就产生顺序不同的效果了

public List<List<Integer>> permute(int[] nums) {
   List<List<Integer>> list = new ArrayList<>();
   // Arrays.sort(nums); // not necessary
   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{
         //代表从nums[i]开始
      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);
      }
   }
} 


猜你喜欢

转载自blog.csdn.net/daimingyang123/article/details/79069971