leetcode-46-Permutations

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

1
2
3
4
5
6
7
8
9
10
11
12
Example:

Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]

试探回溯法

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
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> pms = new ArrayList<>();
rP(nums, new boolean[nums.length], new ArrayList<Integer>(), pms);
return pms;
}

void rP(int[] nums, boolean[] set, List<Integer> pm, List<List<Integer>> pms)
{
if(pm.size() == nums.length)
{
pms.add(pm);
return;
}

for(int i=0; i<nums.length; i++)
{
if(set[i]) continue;
set[i] = true;
List<Integer> currPm = new ArrayList<>(pm);
currPm.add(nums[i]);
rP(nums, set, currPm, pms);
set[i] = false;
}
}
}

Donate? comment?