题目描述

给定一个没有重复数字的序列,返回其所有可能的全排列。

 

样例

输入: [1,2,3]
输出:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

 

思路分析

典型的回溯法,注意剪枝

 

代码及结果

public List<List<Integer>> permute(int[] nums) {
		List<List<Integer>> list = new ArrayList<List<Integer>>();
		List<Integer> list1 = new ArrayList<Integer>();
		dfs(list, list1, nums);
		return list;
	}
void dfs(List<List<Integer>> list, List<Integer> list1, int[] nums){
		if (list1.size() == nums.length) {
			list.add(new ArrayList<Integer>(list1));
		}
		else {
			for (int i = 0; i < nums.length; i++) {
				if (list1.contains(nums[i])) {
					continue;
				}
				list1.add(nums[i]);
				dfs(list, list1, nums);
				list1.remove(list1.size() - 1);
			}
		}
	}

leetcode刷题之旅(46)全排列

相关文章:

  • 2021-06-02
  • 2022-12-23
  • 2021-10-23
  • 2021-06-20
  • 2021-08-25
  • 2021-08-29
  • 2022-12-23
猜你喜欢
  • 2022-01-09
  • 2022-12-23
  • 2021-08-09
  • 2021-07-23
  • 2021-07-22
  • 2021-06-24
相关资源
相似解决方案