Algorithm permutation & backtracking

全排列以及回溯演算法(待完成)

Permutation

Backtracking

My Code

LeetCode

46. Permutations

  • 使用 遞迴
  • 使用 trackBacking (因為要找出所有可能,使用回溯法)
  • 元素皆出現一次

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
    public List<List<Integer>> permute(int[] nums) {
        
        List<List<Integer>> resultList = new ArrayList<>();
        backtracking(resultList, new ArrayList<>(), nums);
        return resultList;
    }

    private void backtracking(List<List<Integer>> resultList, ArrayList tempList, int[] nums) {

        if (tempList.size() == nums.length){
            resultList.add(new ArrayList<>(tempList));
            return;
        }

        for (int num : nums) {

            if (tempList.contains(num)) {
                continue;
            }
            tempList.add(num);
            backtracking(resultList, tempList, nums);

            tempList.remove(tempList.size() - 1);
        }
    }
}
Licensed under CC BY-NC-SA 4.0
comments powered by Disqus