LeetCode-Permutations

题目:https://oj.leetcode.com/problems/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].

源码:Java版本
算法分析:时间复杂度O(n!),空间复杂度O(n)

public class Solution {
    public List<List<Integer>> permute(int[] num) {
        if(num==null || num.length==0) {
            return null;
        }
        List<List<Integer>> results=new ArrayList<List<Integer>>();
        permute(num,0,results);
        return results;
    }
    
    private void permute(int[] num,int index,List<List<Integer>> results) {
        if(index==num.length) {
            List<Integer> list=new ArrayList<Integer>();
            for(int data : num) {
                list.add(data);
            }
            results.add(list);
        }else {
            for(int i=index;i<num.length;i++) {
				swap(num,index,i);
				permute(num,index+1,results);
				swap(num,index,i);
			}
        }
    }
    
    private void swap(int[] num,int x,int y) {
		int temp=num[x];
		num[x]=num[y];
		num[y]=temp;
	}
    
}

你可能感兴趣的:(LeetCode)