本文共 3535 字,大约阅读时间需要 11 分钟。
题目描述
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,[1,1,2]have the following unique permutations:[1,1,2],[1,2,1], and[2,1,1].思路
代码
import java.util.ArrayList;import java.util.Arrays;public class Solution { public ArrayList> permuteUnique(int[] num) { ArrayList > res=new ArrayList<>(); int len=num.length; if(num==null||len==0){ return res; } boolean [] used=new boolean[len]; ArrayList list=new ArrayList<>(); Arrays.sort(num); dfs(list,num,used,res); return res; } public void dfs(ArrayList list,int [] num,boolean [] used,ArrayList > res){ if(list.size()==num.length){ res.add(new ArrayList (list)); return ; } for(int i=0;i 0&&num[i]==num[i-1]&&!used[i-1]){//如果它前一个和它一样的数现在没有被用过,那就跳过, //说明之前那个数已经形成过结果list之一了,目前这个分支处于回溯阶段。。。有点绕,希望能明白 continue; } if(!used[i]){ used[i]=true; list.add(num[i]); dfs(list,num,used,res); list.remove(list.size()-1); used[i]=false; } } }}
题目描述
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index. For example:A =[2,3,1,1,4], returntrue. A =[3,2,1,0,4], returnfalse思路
代码
public class Solution { public boolean canJump(int[] A) { int maxlen=A[0]; for(int i=1;i
题目描述
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. For example:Given array A =[2,3,1,1,4] The minimum number of jumps to reach the last index is2. (Jump1step from index 0 to 1, then3steps to the last index思路
代码
public class Solution { public int jump(int[] A) { int [] dp=new int[A.length];//存放起点到各点的最小步数 for(int i=0;i
思路二
i~furthest_pre
中,区域中的点中能到达的最大位置)所能到达的最大位置(furthest_cur
),当前位置的上一个位置(也是区域)所能到达的最大位置(furthest_pre
),还有就是所走的步数。furthest_cur
是还没有step++的时候,具体结合代码,也就是是一个预判能走到的但还没走的状态。furthest_pre
)之间构成了一块区域,然后我们开始一格一格走,每走一下刷新一下当前这块区域能到的最大位置(furthest_cur
),如果走到从开始位置走到了furthest_pre
那我们也刷新出了最大的furthest_cur
,如果furthest_cur
比终点大,那恭喜!再跳一不就到终点了!可以开始跳一步咯!然后重复上述的动作,直到到达终点。furthest_pre
,那肯定能到一步到它前面那块区域的某一位置,实行下一步跳,跳到furthest_cur
。4 1 6 9 7 4 5 0 6 8 1 2 3 5 8 0 2 1 2
代码
public class Solution { public int jump(int[] A) { int len=A.length; if(len==0||A==null){ return 0; } int furthest_cur=0; int furthest_pre=0; int steps=0; for(int i=0;i=len){ return steps; } if(i>furthest_pre){ furthest_pre=furthest_cur; steps++; } furthest_cur=Math.max(furthest_cur,A[i]+i); } return steps; }}
转载地址:http://gskfl.baihongyu.com/