leetcode--Permutations

Given a collection of numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].

public class Solution {
    public List<List<Integer>> permute(int[] nums) {
		List<List<Integer>> res = new ArrayList<List<Integer>>();
		solve(nums, 0, res);
		return res;
    }
    
	public void solve(int[] nums,int i,List<List<Integer>> res){
		if(i==nums.length-1){
			List<Integer> t = new ArrayList<Integer>();
			for(int j=0;j<nums.length;j++){
				t.add(nums[j]);
			}			
			res.add(t);
		}
		for(int j=i;j<nums.length;j++){
			int t = nums[i];
			nums[i] = nums[j];
			nums[j] = t;
			solve(nums, i+1, res);
			t = nums[i];
			nums[i] = nums[j];
			nums[j] = t;
		}
	}
}

你可能感兴趣的:(leetcode--Permutations)