BiruLyu
6/4/2017 - 11:24 PM

## 46. Permutations(Iterative).java

``````
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = [];
self.backtracking(nums, [], res);
return res;

def backtracking(self, nums, temp, res):

if len(nums) == 0:
return res.append(temp);

for i in range(len(nums)):
self.backtracking(nums[:i] + nums[i+1:] , temp + [nums[i]], res);
``````
``````public class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
dfs(nums, res, 0);
return res;
}

private void dfs(int[] nums, List<List<Integer>> res, int start) {
if (start == nums.length) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
}
return;
}
for (int i = start; i < nums.length; i++) {
swap(nums, i, start);
dfs(nums, res, start + 1);
swap(nums, i, start);
}
}

private void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}
``````
``````public class Solution {
public List<List<Integer>> permute(int[] nums) {

List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> temp = new ArrayList<Integer>();
backtracking(nums, temp, res);
return res;

}

private void backtracking(int[] nums, List<Integer> temp, List<List<Integer>> res) {

if(temp.size() == nums.length) {
return;
}
for(int num : nums) {
if(temp.contains(num)) continue;
backtracking(nums, temp, res);
temp.remove(temp.size() - 1);
}
}
}``````
``````public class Solution {
public List<List<Integer>> permute(int[] num) {
for (int n : num) {
int size = res.size();
for (; size > 0; size--) {
List<Integer> r = res.pollFirst();
for (int i = 0; i <= r.size(); i++) {
List<Integer> t = new ArrayList<Integer>(r);