leetcode--Permutations

来源:互联网 发布:大连知润 编辑:程序博客网 时间:2024/06/07 05:49

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] view plain copy
  1. public class Solution {  
  2.     public List<List<Integer>> permute(int[] nums) {  
  3.         List<List<Integer>> res = new ArrayList<List<Integer>>();  
  4.         solve(nums, 0, res);  
  5.         return res;  
  6.     }  
  7.       
  8.     public void solve(int[] nums,int i,List<List<Integer>> res){  
  9.         if(i==nums.length-1){  
  10.             List<Integer> t = new ArrayList<Integer>();  
  11.             for(int j=0;j<nums.length;j++){  
  12.                 t.add(nums[j]);  
  13.             }             
  14.             res.add(t);  
  15.         }  
  16.         for(int j=i;j<nums.length;j++){  
  17.             int t = nums[i];  
  18.             nums[i] = nums[j];  
  19.             nums[j] = t;  
  20.             solve(nums, i+1, res);  
  21.             t = nums[i];  
  22.             nums[i] = nums[j];  
  23.             nums[j] = t;  
  24.         }  
  25.     }  
  26. }  

原文链接http://blog.csdn.net/crazy__chen/article/details/46388851