您的位置:首页 > 编程语言 > PHP开发

FTPrep, 90 Subsets II

2017-09-27 00:42 197 查看
这是Subset 的 一大类中的一个case。之前分析过了 subset 的基本原型,把代码都分析得比较透彻了。根据输出形式 list in list 很明显是 backtrakcing,要把 item是在for 循环里 +,递归,- (add,递归,remove)的格式。for loop的作用是把每个 元素作为起点进行遍历。OK,这道题中因为要避免duplicate,其实就是说,如果[i+1]==[i],那么就要skip掉[i+1] 没有必要作为起点了。

就在subset (TODO: link) 那道题的基础上加了这么一句,就完成了。所以说要把一类题型的基本原型吃透,其他的变体不过是在这个基础上做一些变化。记得那天我是在跟Yelena视频完之后很快自己做出来的。非常爽。

代码:

class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
if(nums.length==0) return result;
Arrays.sort(nums); // for sure, necessary
List<Integer> item= new ArrayList<>();
backtracking(nums, result, item, 0);
return result;
}

private void backtracking(int[] nums, List<List<Integer>> result, List<Integer> item, int start){
result.add(new ArrayList<Integer>(item));
for(int i=start; i<nums.length; i++){
item.add(nums[i]);
backtracking(nums, result, item, i+1);
item.remove(item.size()-1);
while(i+1<nums.length && nums[i+1]==nums[i]) i++; // I am SMART!!!
// the above is making sure that i will be pointing to the !! LAST !! element in a series of duplicates
// so in the next iteration, the i points to the different number.
// to sum up, 1, for the continuous series of duplicates, use the first elem only,
// that is what the backtracking is doing
// and 2, skip the rest of the duplicates, reach to the last one, that is what the while() loop doing, so in the next loop,
// i points to the new elem.
// by analyzing this, you know why the below code does not work, and just need to add i--; to make it work
// just adding i--; is not okay, since it should be conditional. only when duplicate exist.
// so overall, the following setup is good and easy to use!! keep using it!!!
// boolean dup=false;
// while(i!=start && i<nums.length && nums[i]==nums[i-1]) {i++; dup=true;} // does not work
// if(dup==true) i--;
}
}
}

// 不用多想了,就用这个while inside if 就不错,这样就是个通项公式,take care of everything, 如果while里面需要更多变量很容易出错,因为递归本来就有一定不确定性。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: