第一题 奇偶排队
public static ListNode lineUp(ListNode head) {
if (head == null) {
return head;
}
ListNode single = head;
ListNode doublePre = head.next;
ListNode doubleAfter = head.next;
while (single != null && doubleAfter != null) {
single.next = doubleAfter.next;
single = single.next;
doubleAfter.next = single.next;
doubleAfter = doubleAfter.next;
}
single.next = doublePre;
return head;
}
第二题回溯 拿到数组要排个序
public ArrayList<ArrayList<Integer>> combinationSum (int[] prices, int m) {
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
if(prices == null || prices.length == 0 || m <= 0){
return result;
}
Arrays.sort(prices);
ArrayList<Integer> list = new ArrayList<>();
combination(result, list, prices, m, 0);
return result;
}
public void combination(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> list, int[] prices, int target, int index){
if(target <= 0){
if(target == 0){
result.add(new ArrayList<>(list));
}
return;
}
for(int i = index; i < prices.length; i++){
list.add(prices[i]);
combination(result, list, prices, target - prices[i], i + 1);
list.remove(list.size() - 1);
}
}
全部评论
(0) 回帖