题意:

image.png

解题思路:

  1. 思路:回溯
  2. 1. 从前往后枚举每一位,每一次选择一个没有使用过的数字,然后将该数字置为已使用;
  3. 2. 然后将该数字加入数组中,递归下一层;
  4. 3. 递归终止返回时,将该数字改为“未被使用状态”,并从数组中移除该数字;

PHP代码实现:

  1. class Solution {
  2. public $res = [];
  3. function permute($nums) {
  4. $this->dfs([], $nums);
  5. return $this->res;
  6. }
  7. function dfs($array, $nums) {
  8. if (count($array) == count($nums)) {
  9. array_push($this->res, $array);
  10. return;
  11. }
  12. for ($i = 0; $i < count($nums); $i++) {
  13. if (in_array($nums[$i], $array)) continue;
  14. array_push($array, $nums[$i]);
  15. $this->dfs($array, $nums);
  16. array_pop($array);
  17. }
  18. }
  19. }

GO代码实现:

  1. func permute(nums []int) [][]int {
  2. var pathNums []int
  3. var used = make([]bool, len(nums))
  4. // 清空全局数组(leetcode多次执行全局变量不会消失)
  5. result = [][]int{}
  6. backtrack(nums, pathNums, used)
  7. return result
  8. }
  9. var result [][]int
  10. func backtrack(nums, pathNums []int, used[]bool) {
  11. if len(nums) == len(pathNums) {
  12. tmp := make([]int, len(nums))
  13. // 切片底层公用数据,所以要copy
  14. copy(tmp, pathNums)
  15. result = append(result, tmp)
  16. return
  17. }
  18. for i:=0; i<len(nums); i++ {
  19. // 检查是否访问过
  20. if !used[i] {
  21. used[i] = true
  22. pathNums = append(pathNums, nums[i])
  23. backtrack(nums,pathNums,used)
  24. pathNums = pathNums[:len(pathNums) -1]
  25. used[i] = false
  26. }
  27. }
  28. }