新农上路
- 积分
- 99
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2013-3-6
- 最后登录
- 1970-1-1
|
本帖最后由 Jonson 于 2014-10-11 20:59 编辑
Longford Pairing 既然是一种permutation, 自然就是考虑用DFS, 在DFS的过程中,每次尝试加入一个新的数字到solution中时, 都要check是否满足Longford Pairing的feature, 所以这道题的思路也是一种backtracking的想法。注意需要一个List<List<Integer>>保存结果。- public class LongfordSequence {
- public List<List<Integer>> gernerateSequence(int n) {
- List<List<Integer>> result = new ArrayList<List<Integer>>();
- int[] count = new int[n + 1];
- gernerateHelper(result, new ArrayList<Integer>(), count);
- return result;
- }
- private void gernerateHelper(List<List<Integer>> result, List<Integer> solution, int[] count) {
- if (solution.size() == 2 * (count.length - 1)) {
- result.add(new ArrayList<Integer>(solution));
- return;
- }
- for (int i = 1; i <= count.length - 1; i++) {
- if (count[i] == 0) {
- solution.add(i);
- count[i] = 1;
- gernerateHelper(result, solution, count);
- solution.remove(solution.size() - 1);
- count[i] = 0;
- } else if (count[i] == 1) {
- int size = solution.size();
- if (size - i - 1 >= 0 && solution.get(size - i - 1) == i) {
- solution.add(i);
- count[i] = 2;
- gernerateHelper(result, solution, count);
- solution.remove(solution.size() - 1);
- count[i] = 1;
- }
- }
- }
- }
- }
复制代码 |
|