具有嵌套for循环的递归算法的大O时间复杂度

时间:2017-11-09 22:52:59

标签: java algorithm recursion big-o

我有一个带有两个嵌套for循环的递归算法。我想弄清楚Big-O的时间复杂性是什么。

public Set<Person> getDistinctCombinedPersons(Collection<Person> persons) {
  return permutatePersons(new ArrayList(persons), new HashSet<>(persons));
}
private Set<Person> permutatePersons(List<Person> personList, Set<Person> personSet) {
  if(personList.isEmpty() {
    return personSet;
  }

  Set<Person> deepCopyPersonSet = new HashSet<>(personSet);

  for(Person lPerson : personList) {
    for(Person sPerson : deepCopyPersonSet) {
      Person uniquePerson = CombinePeople.combine(lPerson, sPerson);
      personSet.add(uniquePerson);
    }
  }

  personList.remove(personList.size()-1);

  return permutatePersons(personList, personSet);
}

3 个答案:

答案 0 :(得分:5)

假设您使用长度为permutatePersons的列表调用N,则适用以下递归:

T(N) = T(N-1) + O(N^2)

这是因为在每个递归步骤中,您使用长度为N-1的列表(其中N为当前长度)调用函数,并且还要计算总复杂度O(N ^ 2)(外循环O(N) - 正好遍历列表和内部循环在O(N)-O(1)中遍历每个元素和总N元素的哈希映射,因此嵌套循环总体为O(N ^ 2))。

您可以轻松查看:

T(N) = T(N-1) + O(N^2) = T(N-2) + O(N^2) + O((N-1)^2) =...

= O(n(n+1)(2n+1)/6) = O(n^3)

答案 1 :(得分:0)

对于嵌套循环来说,它看起来像是n ^ 2的大O:

  for(Person lPerson : personList) {
    for(Person sPerson : deepCopyPersonSet) {
      Person uniquePerson = CombinePeople.combine(lPerson, sPerson);
      personSet.add(uniquePerson);
    }
  }

您必须遍历集合中每个元素的每个元素。

然后递归调用有一个很大的O,因为它会为集合中的每个元素调用一次方法。

将两者结合起来:n * n^2会产生大的O ^ n

答案 2 :(得分:0)

因为您有两个嵌套循环,所以运行时复杂度为O(m*n)。这是因为n中的Person - deepCopyPersonSetm次迭代n次。此示例中的PersonpersonListfor(int i = 0, i < m, i++) for(int j = 0, j < n, j++) //your code 的数量。

您的代码基本上是:

public class MainActivity extends AppCompatActivity {
public static final int PICK_IMAGE = 1;
Image picture = new Image();
Context context = getApplicationContext();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button btnGallery = (Button) findViewById(R.id.btnGallery);
    final ImageView imageView = (ImageView) findViewById(R.id.imageView);

    btnGallery.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
            Uri imageUri = intent.getData();
            Bitmap bitmap= MediaStore.Images.Media.getBitmap(context.getContentResolver(), imageUri);
            imageView.setImageBitmap(bitmap);
        }});

对于m的每次迭代,我们都有n次迭代的代码