Permutations leetcode java

题目

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

 

题解

这道题就用循环递归解决子问题。

因为求所有组合,这就意味着不能重复使用元素,要用visited数组。

有因为是所有可能的组合,所以循环length次,就是这里面每位都有可能有length个可能性。

正因为如此,每一层递归就不需要传递一个start点,告诉他从哪开始(因为都是从头开始循环)。

 

代码如下:

 1      public ArrayList<ArrayList<Integer>> permute( int[] num) {
 2         ArrayList<ArrayList<Integer>> res =  new ArrayList<ArrayList<Integer>>();
 3         ArrayList<Integer> item =  new ArrayList<Integer>();
 4         
 5          if(num.length==0||num== null)
 6              return res;
 7          boolean[] visited =  new  boolean[num.length];  
 8         
 9         permutation_helper(num,res,item,visited);
10          return res;
11     }
12     
13      public  void permutation_helper( int[] num, ArrayList<ArrayList<Integer>> res, ArrayList<Integer> item, boolean[] visited){
14          if(item.size()==num.length){
15             res.add( new ArrayList<Integer>(item));
16              return;
17         }
18         
19          for( int i = 0; i<num.length;i++){
20              if(!visited[i]){
21                 item.add(num[i]);
22                 visited[i]= true;
23                 permutation_helper(num,res,item,visited);
24                 item.remove(item.size()-1);
25                 visited[i]= false;
26             }
27         }
28     }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值