Extremely simple Java solution with backtracking


  • 0
    L
    public List<List<Integer>> permute(int[] nums) {
            List<List<Integer>> list = new ArrayList<>();
            helper(nums, new ArrayList<>(), list);
            return list;
        }
        
       private void helper(int[] nums, List<Integer> ll,
          List<List<Integer>> list) {
        if (nums.length == ll.size()) {
          list.add(new ArrayList<>(ll));
          return;
        }
        for (int i = 0; i < nums.length; i++) {
          if (ll.contains(nums[i])) {
            continue;
          }
          ll.add(nums[i]);
          helper(nums, ll, list);
          // backtracking to remove the last placement.
          ll.remove(ll.size() - 1);
        }
      }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.