问题描述
我为置换问题编写了两个函数dfsBackTracking和dfsNoBackTracking,但它们看起来是等效的。
我了解到,在dfsNoBackTracking中,我会存储所有可能的状态,这会导致较高的内存使用率,而dfsBackTracking只会跟踪一个状态,因此内存使用量要少得多。
但是令我感到困惑的是,无论有没有回溯步骤,它们似乎都是等效的。怎么可能?
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
// dfsNoBackTracking(result,nums,new ArrayList<Integer>());
dfsBackTracking(result,new ArrayList<Integer>());
return result;
}
private static void dfsBackTracking(List<List<Integer>> result,int[] nums,List<Integer> currentState)
{
// termination condition
if (currentState.size() == nums.length)
{
result.add(new ArrayList<>(currentState));
return;
}
// all actions :
for (int i = 0; i < nums.length; ++i)
{
// prune for duplicate
if (currentState.contains(nums[i]))
{
continue;
}
currentState.add(nums[i]);
dfsBackTracking(result,currentState);
currentState.remove(currentState.size() - 1); // backtracking step
}
}
private static void dfsNoBackTracking(List<List<Integer>> result,List<Integer> currentState)
{
// termination condition
if (currentState.size() == nums.length)
{
result.add(currentState);
return;
}
// all actions :
for (int i : nums)
{
// prune for duplicate
if (currentState.contains(i))
{
continue;
}
List<Integer> currentStatecopy = new ArrayList<Integer>(currentState);
currentStatecopy.add(i);
dfsNoBackTracking(result,currentStatecopy); // no backtracking step
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)