首页 > 其他 > 详细

[Leetcode]-- Permutations

时间:2014-01-29 14:47:25      阅读:499      评论:0      收藏:0      [点我收藏+]

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].

 

Analysis:

bubuko.com,布布扣

The idea of this classic problem is to use backtracking.
We want to get permutations, which is mainly about swap values in the list.
Consider:
a --> a
ab --> ab, ba
abc --> abc, acb, bac, bca, cab, cba.
...
where for the length of n, the permutations can be generated by
(1) Swap the 1st element with all the elements, including itself.
       (2) Then the 1st element is fixed, go to the next element.
       (3) Until the last element is fixed. Output.
It‘s more clear in the figure above. The key point is to make the big problem into smaller problem, here is how to convert the length n permutation into length n-1 permutation problem.

 

bubuko.com,布布扣
public class Solution {
    public ArrayList<ArrayList<Integer>> permute(int[] num) {
        int len = num.length;
        
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        
        permutation(num, 0, len, result);
        return result;
    }
    
    public void permutation (int[] num, int depth, int len, ArrayList<ArrayList<Integer>> result){
        
        if(depth == len) {
            ArrayList<Integer> list = new ArrayList<Integer>();
            for(int i = 0; i < len; i++){
                list.add(num[i]);
            }
            
            result.add(list);
        }
        
        
        for(int i = depth; i< len; i++){
            int tmp = num[i];
            num[i] = num[depth];
            num[depth] = tmp;
            
            permutation(num, depth + 1, len, result);
            
            tmp = num[i];
            num[i] = num[depth];
            num[depth] = tmp;
        }
    }
}
bubuko.com,布布扣

[Leetcode]-- Permutations

原文:http://www.cnblogs.com/RazerLu/p/3536039.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!