Permutations

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[] num) {
        if(num == null || num.length == 0)  return list;
        int end = num.length;
        helperPermute(num, 0, 0, end);
        return list;
    }
    private List<List<Integer>> list = new ArrayList<List<Integer>>();
    public void helperPermute(int [] num, int count, int start, int end)
    {
        if(count == end)
        {
            List<Integer> rst = new ArrayList<Integer>();
            for(int i : num)
                rst.add(i);
            list.add(rst);
            return;
        }
        for(int i = start; i < end; i++)
        {
            int tmp = num[start];
            num[start] = num[i];
            num[i] = tmp;
            helperPermute(num, count + 1, start + 1, end);
            tmp = num[start];
            num[start] = num[i];
            num[i] = tmp; 
        }
    }
}
View Code

学习之处

  该问题也属于回溯的范畴啊,表现在数字时间进行交换,再尝试完了之后,再交换回来,下面是从维基百科中摘抄的内容。

  回溯法采用试错的思想,它尝试分步的去解决一个问题。在分步解决问题的过程中,当它通过尝试发现现有的分步答案不能得到有效的正确的解答的时候,它将取消上一步甚至是上几步的计算,再通过其它的可能的分步解答再次尝试寻找问题的答案。回溯法通常用最简单的递归方法来实现,在反复重复上述的步骤后可能出现两种情况:

  • 找到一个可能存在的正确的答案
  • 在尝试了所有可能的分步方法后宣告该问题没有答案

  在最坏的情况下,回溯法会导致一次复杂度指数时间的计算。

原文地址:https://www.cnblogs.com/sunshisonghit/p/4320489.html